diff --git a/NOSTR.md b/NOSTR.md index 1bd4d35175f..3a4264d9868 100644 --- a/NOSTR.md +++ b/NOSTR.md @@ -64,6 +64,8 @@ PGPASSWORD=buzz_dev psql -h localhost -U buzz -d buzz -c \ | **Membership notifications** | ✅ | kind:44100 (added) / kind:44101 (removed); relay-signed, community-global scope (`channel_id=None` inside the connected community) | | **Presence (kind:20001)** | ✅ | Ephemeral; arbitrary status string (truncated to 128 chars); writes to Redis (`set_presence`/`clear_presence` on `"offline"`), then fan-out to local subscribers. In multi-community mode presence is scoped to the connected community. | | **Agent presence (kind:20003)** | ✅ | Ephemeral; an owner's presence for the agents it owns, named by `p` tags (at most 256); `online`/`away` set and `offline` clears each agent's presence as its own kind:20001 would. Not fanned out. | +| **Channel access changed (kind:20004)** | ✅ | Ephemeral, relay-signed and relay-only: tells a channel's live subscribers to ask again what they may do there (see [Channel access](#channel-access)). A client may not send it. | +| **Viewer access changed (kind:20005)** | ✅ | Ephemeral, relay-signed, relay-only and `#p`-gated: tells one pubkey, when its community timeout or ban changes, to ask again what it may do in every channel (see [Channel access](#channel-access)). A client may not send it. | | **Typing indicators (kind:20002)** | ✅ | Ephemeral, not stored; published via Redis pub/sub (multi-node capable unlike presence fan-out) | | **NIP-42 authentication** | ✅ | Proactive challenge; optional pubkey allowlist | | **NIP-11 relay info** | ✅ | `GET /` with `Accept: application/nostr+json` | @@ -311,6 +313,72 @@ for its comments. It belongs to the artifact, not to anyone who posts in it. in NIP-11 `supported_extensions`. They also include artifacts in auto-archiving channels in incremental artifact sync. +### Channel access + +A client asks what its signer may do in named channels, and is told when +to ask again. Conversations, channels read through parents and open +channels the signer has not joined all get the same answer. + +- **Asking.** `POST /query` with exactly + `[{"access":"channels","ids":[, ...]}]`: 1 to 100 distinct + lowercase channel IDs. The NIP-98 proof must carry a `payload` tag. Any + other shape is refused with 400. +- **Listing.** Without `ids`, `[{"access":"channels"}]` lists the + channels the signer can reach, ordered by channel ID: the channels they + joined, listed open channels, and the children and grandchildren of + both that the parents' grants reach. These are the channels a read that + names no channel covers, so conversations and unlisted channels stay + out. It is paged: optional `"limit"` (1 to 100, default 100) and + `"after":`, and no other keys. The answer is + `{"channels":[, ...],"next":}`. A page looks + at up to `limit` candidates after `after` and leaves out the ones the + signer cannot read, so it can hold fewer than `limit` and still have a + `next`. To read the next page, send `next` as `after`; `null` means + there are no more. Walking every page lists each channel once. +- **Answer.** For `ids`, a JSON array with one entry per readable channel, + in request order: + `{"id":,"read":true,"post":,"joined":,"role":,"archived":}`. + `joined` is whether the signer has a member row. `role` is the one they + act with: their row's (`owner`, `admin`, `member` or `guest`; a bot acts + as `member`), else an open channel's `join_role`, else what the parents + give, capped at `member`. `archived` is whether the channel itself is + archived. `post` is whether a kind:9 from them would be accepted now: + false for a `guest` role, an archived channel, a conversation whose home + is archived, and a community timeout of the signer or of the agent's + owner, by the same check the post itself meets. While the signer is + timed out, every entry also carries `"timed_out_until":`; + ask again then. A banned signer, or an agent whose owner is banned, is + refused with 403 and the reason, as every request from them is. A channel left out cannot be read: + it is private to them, deleted or missing. If any channel cannot be + 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. +- **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 + every private channel under it, conversations included. A subscription + receives it like any event, so include kind 20004 in the channel's + filter. It goes only to subscribers who can still read the channel; + those who cannot have their subscriptions closed. It is sent for a + member added, removed, leaving, joining or changing role; a change to + visibility, `join_role`, archiving, `parent` or `parent_access`; and an + artifact's move, delete or restore; a channel's deletion; and a + huddle's auto-archive or auto-join. It carries no answer: ask again. It + is best effort, so a client also asks again when it reconnects and when + a post is refused. +- **Ask again everywhere.** When a pubkey's community restriction changes + (a timeout or ban starts or is lifted, by any route: a moderation + command, the admin API or a resolved report), or an agent's owner is + recorded, the relay sends an ephemeral kind:20005, signed by the relay, + with empty content and only `["p", ]`, to that pubkey and to each + agent it owns. Subscribe with `{"kinds":[20005],"#p":[]}`; + the kind is `#p`-gated, so it reaches no one else. It carries no answer: + ask again about every channel. A timeout that runs out sends nothing; + `timed_out_until` says when to ask. +- Relays that support this advertise `buzz-channel-access` in NIP-11 + `supported_extensions`. Without it, a client cannot learn whether it may + post in a channel it has not joined. + ### Default channels A community's owners and admins can mark a channel as a **default channel**: diff --git a/crates/buzz-core/src/kind.rs b/crates/buzz-core/src/kind.rs index 26d85177a0f..2fe168e4059 100644 --- a/crates/buzz-core/src/kind.rs +++ b/crates/buzz-core/src/kind.rs @@ -191,6 +191,7 @@ pub const RESULT_GATED_KINDS: &[u32] = &[ KIND_AGENT_TURN_METRIC, KIND_MEMBER_ADDED_NOTIFICATION, KIND_MEMBER_REMOVED_NOTIFICATION, + KIND_VIEWER_ACCESS_CHANGED, ]; /// Kinds whose stored events have `#p`-bound read access — readable only by @@ -218,6 +219,7 @@ pub const P_GATED_KINDS: &[u32] = &[ // readable by any unauthenticated or non-owner party, including via `ids` // filters — see NIP-AM §Relay Behavior. KIND_AGENT_TURN_METRIC, + KIND_VIEWER_ACCESS_CHANGED, ]; /// NIP-AP: Agent Persona (parameterized replaceable, owner-authored). @@ -528,6 +530,14 @@ pub const KIND_TYPING_INDICATOR: u32 = 20002; /// Ephemeral: an owner's presence for its agents. Content is the status, each /// `p` tag names one agent the signer owns. Never the signer's own presence. pub const KIND_AGENT_PRESENCE: u32 = 20003; +/// Ephemeral, relay-signed: "ask again what you may do in this channel" +/// (NOSTR.md, Channel access). Empty content; only `["h", ]`. +pub const KIND_CHANNEL_ACCESS_CHANGED: u32 = 20004; +/// Ephemeral, relay-signed: "ask again what you may do in every channel", +/// sent when the named person's community restriction changes +/// (NOSTR.md, Channel access). Empty content; only `["p", ]`, and +/// delivered only to that pubkey. +pub const KIND_VIEWER_ACCESS_CHANGED: u32 = 20005; /// Ephemeral: owner-scoped encrypted agent observer telemetry and control frame. pub const KIND_AGENT_OBSERVER_FRAME: u32 = 24200; /// Ephemeral: huddle emoji reaction burst. Channel-scoped to the ephemeral @@ -768,6 +778,8 @@ pub const ALL_KINDS: &[u32] = &[ KIND_PRESENCE_UPDATE, KIND_TYPING_INDICATOR, KIND_AGENT_PRESENCE, + KIND_CHANNEL_ACCESS_CHANGED, + KIND_VIEWER_ACCESS_CHANGED, KIND_HUDDLE_REACTION, KIND_BLOSSOM_AUTH, KIND_OPERATOR_LISTENER_REGISTRATION, @@ -934,6 +946,8 @@ pub const fn is_relay_only_kind(kind: u32) -> bool { | KIND_THREAD_WINDOW_BOUNDS | KIND_MEMBERSHIP_SNAPSHOT | KIND_MEMBERSHIP_PUBLIC + | KIND_CHANNEL_ACCESS_CHANGED + | KIND_VIEWER_ACCESS_CHANGED ) } @@ -1024,6 +1038,18 @@ mod tests { assert!(!is_relay_only_kind(KIND_NIP43_LEAVE_REQUEST)); } + #[test] + fn channel_access_changed_is_relay_only_and_ephemeral() { + assert_eq!(KIND_CHANNEL_ACCESS_CHANGED, 20004); + assert!(is_relay_only_kind(KIND_CHANNEL_ACCESS_CHANGED)); + assert!(is_ephemeral(KIND_CHANNEL_ACCESS_CHANGED)); + assert_eq!(KIND_VIEWER_ACCESS_CHANGED, 20005); + assert!(is_relay_only_kind(KIND_VIEWER_ACCESS_CHANGED)); + assert!(is_ephemeral(KIND_VIEWER_ACCESS_CHANGED)); + assert!(RESULT_GATED_KINDS.contains(&KIND_VIEWER_ACCESS_CHANGED)); + assert!(P_GATED_KINDS.contains(&KIND_VIEWER_ACCESS_CHANGED)); + } + #[test] fn thread_window_bounds_is_relay_only() { assert_eq!(KIND_THREAD_WINDOW_BOUNDS, 39007); diff --git a/crates/buzz-relay/src/api/admin/mod.rs b/crates/buzz-relay/src/api/admin/mod.rs index c29797185b6..8466dfd4109 100644 --- a/crates/buzz-relay/src/api/admin/mod.rs +++ b/crates/buzz-relay/src/api/admin/mod.rs @@ -1305,7 +1305,7 @@ async fn unban_member( if !lifted { return Err(ApiError::conflict("no active ban for this member")); } - state.invalidate_restrictions(&tenant); + state.restrictions_changed(&tenant, Some(&target_bytes)); Ok(axum::http::StatusCode::NO_CONTENT) } @@ -1348,7 +1348,7 @@ async fn untimeout_member( if !lifted { return Err(ApiError::conflict("no active timeout for this member")); } - state.invalidate_restrictions(&tenant); + state.restrictions_changed(&tenant, Some(&target_bytes)); Ok(axum::http::StatusCode::NO_CONTENT) } @@ -2283,10 +2283,19 @@ mod postgres_tests { /// routes that hit the DB can commit and read back results. pub(super) async fn nip98_state_with_real_pool( pool: sqlx::PgPool, + ) -> Arc { + nip98_state_with_real_pool_and_redis(pool, "redis://127.0.0.1:1").await + } + + /// [`nip98_state_with_real_pool`] on the Redis at `redis_url`, for + /// tests that watch what a route publishes. + async fn nip98_state_with_real_pool_and_redis( + pool: sqlx::PgPool, + redis_url: &str, ) -> Arc { let mut config = crate::config::Config::for_test(); // [FI-TRACE-ENV-RACE] config.require_relay_membership = false; - config.redis_url = "redis://127.0.0.1:1".to_string(); + config.redis_url = redis_url.to_string(); config.relay_operator_pubkeys = vec![test_operator_keys().public_key().to_hex()]; config.relay_operator_api_origin = Some("https://admin.example".to_string()); config.admin = Some(crate::config::AdminConfig { @@ -12679,6 +12688,84 @@ mod postgres_tests { ); } + /// A timeout or ban set from the dashboard is pushed to the person and + /// their agent, so their clients ask again whether they may post, and to + /// no one else. The route reaches the push only through the one step + /// every restriction change takes. + /// Mutation: drop the push from `AppState::restrictions_changed` → RED. + #[tokio::test] + #[ignore = "requires Postgres and Redis"] + async fn direct_timeout_and_ban_are_pushed_to_that_person_only() { + use crate::handlers::channel_access_postgres_tests::{subscribe_viewer, viewer_pushes}; + let (pool, community, host, _) = direct_fixture().await; + let redis_url = std::env::var("REDIS_URL").expect("REDIS_URL names a live Redis"); + let state = nip98_state_with_real_pool_and_redis(pool, &redis_url).await; + tokio::spawn(state.pubsub.clone().run_subscriber()); + crate::handlers::multinode_fanout::spawn(state.clone(), state.pubsub.subscribe_local()); + let tenant = buzz_core::TenantContext::resolved(community, &host); + let (member, agent, bystander) = ( + nostr::Keys::generate(), + nostr::Keys::generate(), + nostr::Keys::generate(), + ); + for keys in [&member, &agent] { + state + .db + .ensure_user(community, keys.public_key().as_bytes()) + .await + .expect("user"); + } + state + .db + .set_agent_owner( + community, + agent.public_key().as_bytes(), + member.public_key().as_bytes(), + ) + .await + .expect("agent owner"); + let mut member_rx = subscribe_viewer(&state, &tenant, &member, true); + let mut agent_rx = subscribe_viewer(&state, &tenant, &agent, true); + let mut bystander_rx = subscribe_viewer(&state, &tenant, &bystander, false); + state + .pubsub + .retain_topic(&tenant, buzz_pubsub::EventTopic::Global) + .await; + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let target = member.public_key().to_hex(); + let wait = std::time::Duration::from_secs(2); + + for (path, body) in [ + ( + format!("/members/{target}/timeout?communityHost={host}"), + serde_json::json!({ "requestId": Uuid::new_v4(), "expirationSecs": 600 }), + ), + ( + format!("/members/{target}/ban?communityHost={host}"), + serde_json::json!({ "requestId": Uuid::new_v4() }), + ), + ] { + let (status, answer) = direct_post(&state, &path, body).await; + assert_eq!(status, StatusCode::OK, "{path}: {answer}"); + assert_eq!( + viewer_pushes(&state, &mut member_rx, wait).await, + vec![target.clone()], + "{path}" + ); + assert_eq!( + viewer_pushes(&state, &mut agent_rx, wait).await, + vec![agent.public_key().to_hex()], + "{path}" + ); + } + assert!( + viewer_pushes(&state, &mut bystander_rx, wait) + .await + .is_empty(), + "a bystander is told nothing" + ); + } + /// A ban whose mutation committed before a crash still disconnects the /// target when recovery resumes past the ban step. #[tokio::test] diff --git a/crates/buzz-relay/src/api/bridge.rs b/crates/buzz-relay/src/api/bridge.rs index 31cae9b12b8..83f59faa376 100644 --- a/crates/buzz-relay/src/api/bridge.rs +++ b/crates/buzz-relay/src/api/bridge.rs @@ -3,6 +3,7 @@ //! These endpoints provide HTTP access to the relay's Nostr protocol, //! authenticated via NIP-98 signed events. +mod channel_access; mod effective_edit; mod membership_snapshot; mod read_state_snapshot; @@ -1640,8 +1641,9 @@ pub async fn query_events( // This authority surface always needs payload-bound NIP-98, including dev. // Detect before admission, and before Filter can drop the extension key. - let compact_membership = serde_json::from_slice::>(&body) - .is_ok_and(|filters| membership_snapshot::requested(&filters)); + let payload_bound = serde_json::from_slice::>(&body).is_ok_and(|filters| { + membership_snapshot::requested(&filters) || channel_access::requested(&filters) + }); // NIP-FI admission. [FI-TRACE-AUTHORITY-UNIFORM] let proof = crate::nip_fi_shadow::EnforcedProof::new(&state, &headers, "bridge"); @@ -1657,8 +1659,8 @@ pub async fn query_events( "POST", &url, Some(&body), - state.config.require_auth_token || nip_fi_active || compact_membership, - nip_fi_enforce || compact_membership, + state.config.require_auth_token || nip_fi_active || payload_bound, + nip_fi_enforce || payload_bound, )) .map(|auth| auth.proof((auth.event_id_bytes, auth.signed_created_at))) .map_err(|e| e.into_response()) @@ -1748,6 +1750,9 @@ async fn query_member_events( ) .await; } + if channel_access::requested(&raw_filters) { + return channel_access::query(state, tenant, &pubkey, &raw_filters).await; + } let routed = || caller.read_artifact(&raw_filters); if let Some(result) = super::artifact::query(state, tenant, &pubkey, &raw_filters, false, routed).await diff --git a/crates/buzz-relay/src/api/bridge/channel_access.rs b/crates/buzz-relay/src/api/bridge/channel_access.rs new file mode 100644 index 00000000000..a0cb3317664 --- /dev/null +++ b/crates/buzz-relay/src/api/bridge/channel_access.rs @@ -0,0 +1,209 @@ +//! `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). + +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::state::AppState; + +/// How long one answer may take before the request fails and is retried. +const DEADLINE: std::time::Duration = std::time::Duration::from_secs(8); + +pub(super) fn requested(filters: &[Value]) -> bool { + filters.iter().any(|f| f.get("access").is_some()) +} + +/// What a request asks about. +#[derive(Debug, PartialEq, Eq)] +enum Asked { + /// The named channels, in request order. + Named(Vec), + /// One page of the channels the signer can reach. + Reachable { after: Option, limit: usize }, +} + +/// 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) +} + +/// 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 +/// [`MAX_IDS`], default [`MAX_IDS`]). +fn asked(filters: &[Value]) -> Result { + const SHAPE: &str = "channel access requires one filter with \ + {\"access\":\"channels\"} and either \ + \"ids\":[1 to 100 distinct lowercase channel ids] \ + or optionally \"after\": and \"limit\":<1 to 100>"; + let [Value::Object(filter)] = filters else { + return Err(SHAPE); + }; + if filter.get("access").and_then(Value::as_str) != Some("channels") { + return Err(SHAPE); + } + let Some(raw) = filter.get("ids") else { + if filter + .keys() + .any(|key| !matches!(key.as_str(), "access" | "after" | "limit")) + { + return Err(SHAPE); + } + let after = match filter.get("after") { + None => None, + Some(value) => Some(channel_id(value).ok_or(SHAPE)?), + }; + let limit = match filter.get("limit") { + None => MAX_IDS, + Some(value) => value + .as_u64() + .filter(|limit| (1..=MAX_IDS as u64).contains(limit)) + .ok_or(SHAPE)? as usize, + }; + return Ok(Asked::Reachable { after, limit }); + }; + let Value::Array(raw) = raw else { + return Err(SHAPE); + }; + if filter.len() != 2 || raw.is_empty() || raw.len() > MAX_IDS { + return Err(SHAPE); + } + let mut ids = Vec::with_capacity(raw.len()); + for value in raw { + let id = channel_id(value).ok_or(SHAPE)?; + if ids.contains(&id) { + return Err(SHAPE); + } + ids.push(id); + } + Ok(Asked::Named(ids)) +} + +pub(super) async fn query( + state: &AppState, + tenant: &TenantContext, + viewer: &nostr::PublicKey, + filters: &[Value], +) -> Result, (StatusCode, Json)> { + let asked = asked(filters).map_err(|e| api_error(StatusCode::BAD_REQUEST, e))?; + let (community, pubkey) = (tenant.community(), viewer.to_bytes()); + let answered = tokio::time::timeout(DEADLINE, async { + match asked { + Asked::Named(ids) => answer(state, community, &pubkey, &ids) + .await + .map(serde_json::to_value), + Asked::Reachable { after, limit } => reachable(state, community, &pubkey, after, limit) + .await + .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", + ) + })?; + Ok(Json(encoded.map_err(|_| { + api_error( + StatusCode::INTERNAL_SERVER_ERROR, + "error: channel access encoding failed", + ) + })?)) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + const A: &str = "8c1f3d2e-4b5a-4c6d-9e7f-0a1b2c3d4e5f"; + const B: &str = "3f3e3cd7-3b56-81d9-8dd2-8d8b5b1f6d57"; + + #[test] + fn accepts_only_the_exact_shape() { + assert_eq!( + asked(&[json!({"access":"channels","ids":[A, B]})]).unwrap(), + Asked::Named(vec![ + Uuid::parse_str(A).unwrap(), + Uuid::parse_str(B).unwrap() + ]) + ); + assert_eq!( + asked(&[json!({"access":"channels"})]).unwrap(), + Asked::Reachable { + after: None, + limit: MAX_IDS + } + ); + assert_eq!( + asked(&[json!({"access":"channels","after":A,"limit":1})]).unwrap(), + Asked::Reachable { + after: Some(Uuid::parse_str(A).unwrap()), + limit: 1 + } + ); + let too_many: Vec = (0..=MAX_IDS).map(|_| Uuid::new_v4().to_string()).collect(); + for refused in [ + json!([]), + json!([{"access":"channels","ids":[A]}, {"access":"channels","ids":[B]}]), + json!([{"access":"channel","ids":[A]}]), + json!([{"access":"channels","ids":[A],"kinds":[9]}]), + json!([{"access":"channels","ids":[]}]), + json!([{"access":"channels","ids":too_many}]), + json!([{"access":"channels","ids":[A, A]}]), + json!([{"access":"channels","ids":[A.to_uppercase()]}]), + json!([{"access":"channels","ids":[A.replace('-', "")]}]), + json!([{"access":"channels","ids":[7]}]), + json!([{"access":"channels","ids":A}]), + json!([{"access":"channels","kinds":[9]}]), + json!([{"access":"channels","ids":null}]), + json!([{"access":"channels"}, {"access":"channels"}]), + json!([{"access":"channels","limit":0}]), + json!([{"access":"channels","limit":101}]), + json!([{"access":"channels","limit":"5"}]), + json!([{"access":"channels","limit":2.5}]), + json!([{"access":"channels","after":A.to_uppercase()}]), + json!([{"access":"channels","after":null}]), + json!([{"access":"channels","ids":[A],"after":B}]), + json!([{"access":"channels","ids":[A],"limit":1}]), + ] { + 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. + #[tokio::test] + async fn a_failed_lookup_fails_the_whole_request() { + let state = crate::state::tests::test_state_with_database_url_and_pool_options( + "postgres://nobody@127.0.0.1:1/none", + sqlx::postgres::PgPoolOptions::new() + .acquire_timeout(std::time::Duration::from_millis(200)), + ) + .await; + let tenant = TenantContext::resolved( + buzz_core::CommunityId::from_uuid(Uuid::new_v4()), + "fail.test", + ); + let viewer = nostr::Keys::generate().public_key(); + let filters = [json!({"access":"channels","ids":[A, B]})]; + let (status, Json(body)) = query(&state, &tenant, &viewer, &filters) + .await + .expect_err("no answer without the database"); + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); + assert!(body["error"].as_str().unwrap().contains("retry"), "{body}"); + } +} diff --git a/crates/buzz-relay/src/audio/handler.rs b/crates/buzz-relay/src/audio/handler.rs index f91397e9a55..731c5dc3147 100644 --- a/crates/buzz-relay/src/audio/handler.rs +++ b/crates/buzz-relay/src/audio/handler.rs @@ -2517,7 +2517,13 @@ impl crate::audio::room::RoomEndHandler for CommittedRoomEnd { }) .await { - Ok(true) => {} + Ok(true) => { + crate::handlers::channel_access::announce_changed( + &self.tenant, + &state, + room.channel_id, + ); + } Ok(false) => return true, Err(error) => { warn!(channel_id = %room.channel_id, %error, "auto-archive failed, huddle stays alive"); @@ -3989,6 +3995,7 @@ async fn commit_participant_join( MembershipAdmission::AutoAddRequired { .. } ) { state.invalidate_membership(tenant, channel_id, pubkey_bytes); + crate::handlers::channel_access::announce_changed(tenant, state, channel_id); } Ok(outcome) diff --git a/crates/buzz-relay/src/handlers/artifact_conversation_postgres_tests.rs b/crates/buzz-relay/src/handlers/artifact_conversation_postgres_tests.rs index eceb12aa0a7..d28be56613d 100644 --- a/crates/buzz-relay/src/handlers/artifact_conversation_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/artifact_conversation_postgres_tests.rs @@ -20,7 +20,11 @@ use crate::handlers::parent_access_postgres_tests::{ use crate::state::AppState; /// Ingest `event` as its signer; `Err` carries the refusal. -async fn send(state: &Arc, tenant: &TenantContext, event: Event) -> Result<(), String> { +pub(crate) async fn send( + state: &Arc, + tenant: &TenantContext, + event: Event, +) -> Result<(), String> { let auth = IngestAuth::Http { pubkey: event.pubkey, scopes: vec![ @@ -39,7 +43,7 @@ async fn send(state: &Arc, tenant: &TenantContext, event: Event) -> Re } /// A `buzz.task` revision of `id` in `home`, signed by `key`. -fn task(key: &Keys, home: Uuid, id: Uuid, op: &str, prev: Option<&Event>) -> Event { +pub(crate) fn task(key: &Keys, home: Uuid, id: Uuid, op: &str, prev: Option<&Event>) -> Event { let mut tags = vec![ vec!["ar".to_owned(), "1".into()], vec!["d".into(), id.to_string()], @@ -60,7 +64,7 @@ fn task(key: &Keys, home: Uuid, id: Uuid, op: &str, prev: Option<&Event>) -> Eve } /// Create a task in `home` as `key`: its ID and create revision. -async fn create_task( +pub(crate) async fn create_task( state: &Arc, tenant: &TenantContext, key: &Keys, @@ -86,7 +90,7 @@ fn open_event(key: &Keys, artifact: &str, h: Uuid) -> Event { } /// Open `artifact`'s conversation as `key`, at its derived address. -async fn open( +pub(crate) async fn open( state: &Arc, tenant: &TenantContext, key: &Keys, diff --git a/crates/buzz-relay/src/handlers/channel_access.rs b/crates/buzz-relay/src/handlers/channel_access.rs new file mode 100644 index 00000000000..52d246f08fc --- /dev/null +++ b/crates/buzz-relay/src/handlers/channel_access.rs @@ -0,0 +1,312 @@ +//! What one viewer may do in named channels (NOSTR.md, Channel access), and +//! the push that tells live subscribers to ask again. +//! +//! The answer applies the rules the read and post gates apply +//! ([`super::ingest::check_channel_membership`], [`super::ingest::may_post`], +//! [`super::ingest::closed_by_archive`]). It is a snapshot: every post is +//! still checked when it arrives. + +use buzz_core::channel::MemberRole; +use buzz_core::kind::{ + KIND_CHANNEL_ACCESS_CHANGED, KIND_STREAM_MESSAGE, KIND_VIEWER_ACCESS_CHANGED, +}; +use buzz_core::{CommunityId, TenantContext}; +use buzz_db::channel::{ChannelJoinRole, ChannelRecord}; +use futures_util::stream::{self, StreamExt, TryStreamExt}; +use nostr::{EventBuilder, Kind, Tag}; +use serde::Serialize; +use tracing::warn; +use uuid::Uuid; + +use crate::state::AppState; + +/// The most channels one request may name, and the most one page lists. +pub const MAX_IDS: usize = 100; + +/// One readable channel's answer for the viewer. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct ChannelAccess { + /// The channel. + pub id: Uuid, + /// Always true: unreadable channels are left out. + pub read: bool, + /// Whether a kind:9 from the viewer would be accepted now. + pub post: bool, + /// Whether the viewer has an active member row. + pub joined: bool, + /// The role the viewer acts with: their row's, else an open channel's + /// `join_role`, else what the parents give. + pub role: &'static str, + /// Whether the channel itself is archived. + pub archived: bool, + /// While the viewer is timed out in the community, when that ends (unix + /// seconds). `post` is false until then; ask again at that time. + #[serde(skip_serializing_if = "Option::is_none")] + pub timed_out_until: Option, +} + +/// One page of the channels a viewer can reach. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct ReachablePage { + /// The readable channels of this page, ordered by id. + pub channels: Vec, + /// The `after` for the next page, or `None` when there are no more. + pub next: Option, +} + +/// Whether the viewer's community restriction lets a kind:9 through now. +#[derive(Debug, Clone, Copy)] +struct Restriction { + may_post: bool, + timed_out_until: Option, +} + +/// The write-path restriction verdict ingest applies to a kind:9 +/// ([`super::ingest::write_restriction_denial`]), read fresh so an answer +/// given right after a timeout push is not a stale cached row. +async fn restriction( + state: &AppState, + community_id: CommunityId, + pubkey: &[u8], +) -> Result { + let restriction = state + .db + .moderation_restriction_state(community_id, pubkey) + .await?; + let now = chrono::Utc::now(); + let refused = + super::ingest::write_restriction_denial(KIND_STREAM_MESSAGE, &restriction, now).is_some(); + let timed_out_until = restriction + .muted_until + .filter(|until| refused && !restriction.banned && *until > now) + .map(|until| until.timestamp()); + Ok(Restriction { + may_post: !refused, + timed_out_until, + }) +} + +/// The viewer's answer for each readable channel in `ids`, in request order. +/// Unreadable channels are left out; any lookup failure fails the whole +/// batch, so a missing entry always means "cannot read". +pub(crate) async fn answer( + state: &AppState, + community_id: CommunityId, + pubkey: &[u8], + ids: &[Uuid], +) -> Result, buzz_db::DbError> { + // A push can arrive before another node has dropped its cached rows for + // this viewer, so this node reads them fresh. + state.invalidate_membership_local(community_id, Uuid::nil(), pubkey); + let restriction = restriction(state, community_id, pubkey).await?; + // The channels are independent reads: overlap a few, in request order, + // without monopolising the pool. + let answers: Vec> = stream::iter(ids.iter().copied()) + .map(|id| access(state, community_id, pubkey, id, restriction)) + .buffered(super::req::FILTER_QUERY_CONCURRENCY) + .try_collect() + .await?; + Ok(answers.into_iter().flatten().collect()) +} + +/// One page of the viewer's answers for the channels they can reach, ordered +/// by id, starting after `after`: channels they joined, listed open +/// channels, and the children and grandchildren of both. These are the +/// channels a read that names none covers, so artifact conversations and +/// unlisted channels stay out. A page looks at up to `limit` candidates and +/// leaves out the unreadable ones, so it can hold fewer than `limit` and +/// still have a `next`. +pub(crate) async fn reachable( + state: &AppState, + community_id: CommunityId, + pubkey: &[u8], + after: Option, + limit: usize, +) -> Result { + let mut ids = state + .db + .get_accessible_channel_ids(community_id, pubkey) + .await?; + ids.retain(|id| after.is_none_or(|after| *id > after)); + ids.sort_unstable(); + let next = (ids.len() > limit).then(|| ids[limit - 1]); + ids.truncate(limit); + let channels = answer(state, community_id, pubkey, &ids).await?; + Ok(ReachablePage { channels, next }) +} + +fn role_name(role: MemberRole) -> &'static str { + match role { + MemberRole::Owner => "owner", + MemberRole::Admin => "admin", + MemberRole::Member => "member", + MemberRole::Guest => "guest", + // The contract has no bot role: a bot acts as a member. + MemberRole::Bot => "member", + } +} + +/// `pubkey`'s access to `channel_id` under their community `restriction`; +/// `None` when they cannot read it, whether it is private, deleted or missing. +async fn access( + state: &AppState, + community_id: CommunityId, + pubkey: &[u8], + channel_id: Uuid, + restriction: Restriction, +) -> Result, buzz_db::DbError> { + let channel = match state + .db + .get_channel_for_event_write(community_id, channel_id) + .await + { + Ok(channel) if channel.deleted_at.is_none() => channel, + Ok(_) | Err(buzz_db::DbError::ChannelNotFound(_)) => return Ok(None), + Err(e) => return Err(e), + }; + let Some((role, joined)) = acting_role(state, community_id, &channel, pubkey).await? else { + return Ok(None); + }; + let post = role.can_post() + && restriction.may_post + && !super::ingest::closed_by_archive(community_id, state, &channel).await?; + Ok(Some(ChannelAccess { + id: channel_id, + read: true, + post, + joined, + role: role_name(role), + archived: channel.archived_at.is_some(), + timed_out_until: restriction.timed_out_until, + })) +} + +/// The role `pubkey` acts with in `channel` and whether it is their own +/// row's, or `None` when they cannot read it. Mirrors +/// [`super::ingest::may_post`]: an active row's role, else an open channel's +/// `join_role` (failing closed to guest), else what the parents give. A row +/// removed between the two reads counts as no row. +async fn acting_role( + state: &AppState, + community_id: CommunityId, + channel: &ChannelRecord, + pubkey: &[u8], +) -> Result, buzz_db::DbError> { + if state + .is_member_cached(community_id, channel.id, pubkey) + .await? + { + let role = state + .db + .get_member_role(community_id, channel.id, pubkey) + .await?; + if let Some(role) = role.and_then(|r| r.parse().ok()) { + return Ok(Some((role, true))); + } + } + if channel.visibility == "open" { + let role = match ChannelJoinRole::parse_fail_closed(&channel.join_role) { + ChannelJoinRole::Member => MemberRole::Member, + ChannelJoinRole::Guest => MemberRole::Guest, + }; + return Ok(Some((role, false))); + } + Ok( + super::parent_access::inherited_role(state, community_id, channel, pubkey) + .await? + .map(|role| (role, false)), + ) +} + +/// Tell live subscribers of `channel` and of every private channel under it, +/// whose readers can come from it, to ask again. Call after a committed +/// change to who may read or post there, once per change. The pushes are +/// sent off the caller's path, best effort: a failure is logged, and a +/// client also asks again when it reconnects or a post is refused. Fan-out +/// delivers a push only to subscribers who can still read the channel; the +/// eviction beside each change closes the rest. Open channels under it are +/// not told: their access does not come from parents. +pub fn announce_changed(tenant: &TenantContext, state: &AppState, channel: Uuid) { + let (tenant, db, pubsub, keys) = ( + tenant.clone(), + state.db.clone(), + state.pubsub.clone(), + state.relay_keypair.clone(), + ); + tokio::spawn(async move { + let mut channels = vec![channel]; + match db + .get_private_descendant_ids(tenant.community(), channel) + .await + { + Ok(descendants) => channels.extend(descendants), + Err(e) => warn!(%channel, error = %e, "channel access push: descendant read failed"), + } + for channel in channels { + let tag = Tag::parse(["h".to_string(), channel.to_string()]).expect("h tag"); + let event = + match EventBuilder::new(Kind::Custom(KIND_CHANNEL_ACCESS_CHANGED as u16), "") + .tags([tag]) + .sign_with_keys(&keys) + { + Ok(event) => event, + Err(e) => { + warn!(%channel, error = %e, "channel access push: signing failed"); + continue; + } + }; + if let Err(e) = pubsub + .publish_event(&tenant, buzz_pubsub::EventTopic::Channel(channel), &event) + .await + { + warn!(%channel, error = %e, "channel access push failed"); + } + } + }); +} + +/// Tell `pubkey` and every agent it owns, and no one else, to ask again +/// what they may do in every channel: an agent is restricted by its owner's +/// row. Sent only by [`AppState::restrictions_changed`], the step every +/// restriction change passes through. Off the caller's path, best effort +/// like [`announce_changed`]. The kind is p-gated, so only the named pubkey +/// may subscribe to it or receive it. +pub(crate) fn announce_restriction_changed( + tenant: &TenantContext, + state: &AppState, + pubkey: &[u8], +) { + let (tenant, db, pubsub, keys, pubkey) = ( + tenant.clone(), + state.db.clone(), + state.pubsub.clone(), + state.relay_keypair.clone(), + pubkey.to_vec(), + ); + tokio::spawn(async move { + let mut viewers = vec![pubkey.clone()]; + match db.list_agents_for_owner(tenant.community(), &pubkey).await { + Ok(agents) => viewers.extend(agents), + Err(e) => warn!(error = %e, "viewer access push: agent read failed"), + } + for viewer in viewers { + let tag = Tag::parse(["p".to_string(), hex::encode(&viewer)]).expect("p tag"); + let event = match EventBuilder::new(Kind::Custom(KIND_VIEWER_ACCESS_CHANGED as u16), "") + .tags([tag]) + .sign_with_keys(&keys) + { + Ok(event) => event, + Err(e) => { + warn!(error = %e, "viewer access push: signing failed"); + continue; + } + }; + if let Err(e) = pubsub + .publish_event(&tenant, buzz_pubsub::EventTopic::Global, &event) + .await + { + warn!(error = %e, "viewer access push failed"); + } + } + }); +} diff --git a/crates/buzz-relay/src/handlers/channel_access_postgres_tests.rs b/crates/buzz-relay/src/handlers/channel_access_postgres_tests.rs new file mode 100644 index 00000000000..83383a7a008 --- /dev/null +++ b/crates/buzz-relay/src/handlers/channel_access_postgres_tests.rs @@ -0,0 +1,1016 @@ +//! Postgres-backed tests for the channel access answer (NOSTR.md, Channel +//! access): every answer goes through the real `POST /query` route with a +//! payload-bound NIP-98 proof, every change through real ingest, and the +//! push through Redis and the real multi-node fan-out. + +use std::sync::Arc; +use std::time::Duration; + +use axum::body::{to_bytes, Body}; +use axum::extract::ws::Message; +use axum::http::{Request, StatusCode}; +use base64::Engine; +use buzz_core::TenantContext; +use nostr::{EventBuilder, Keys, Kind, Tag}; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use tower::ServiceExt; +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::state::AppState; +use buzz_core::kind::{KIND_CHANNEL_ACCESS_CHANGED, KIND_VIEWER_ACCESS_CHANGED}; + +/// `POST /query` asking what `viewer` may do in `ids`, signed with a payload +/// tag unless `payload` is false. +async fn ask_with( + state: &Arc, + tenant: &TenantContext, + viewer: &Keys, + ids: &[Uuid], + payload: bool, +) -> (StatusCode, Value) { + let body = json!([{"access": "channels", "ids": ids}]); + query(state, tenant, viewer, &body, payload).await +} + +/// `POST /query` with `body`, signed by `viewer`, with a payload tag unless +/// `payload` is false. +async fn query( + state: &Arc, + tenant: &TenantContext, + viewer: &Keys, + body: &Value, + payload: bool, +) -> (StatusCode, Value) { + let bytes = serde_json::to_vec(&body).unwrap(); + let host = tenant.host(); + let mut tags = vec![ + Tag::parse([ + "u", + &crate::api::bridge::nip98_expected_url(&state.config.relay_url, tenant, "/query"), + ]) + .unwrap(), + Tag::parse(["method", "POST"]).unwrap(), + Tag::parse(["nonce", &Uuid::new_v4().to_string()]).unwrap(), + ]; + if payload { + tags.push(Tag::parse(["payload", &hex::encode(Sha256::digest(&bytes))]).unwrap()); + } + let proof = EventBuilder::new(Kind::Custom(27235), "") + .tags(tags) + .sign_with_keys(viewer) + .unwrap(); + let auth = format!( + "Nostr {}", + base64::engine::general_purpose::STANDARD.encode(serde_json::to_vec(&proof).unwrap()) + ); + let response = crate::router::build_router(state.clone()) + .oneshot( + Request::builder() + .method("POST") + .uri("/query") + .header("host", host) + .header("authorization", auth) + .body(Body::from(bytes)) + .unwrap(), + ) + .await + .unwrap(); + let status = response.status(); + let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + (status, serde_json::from_slice(&body).unwrap_or(Value::Null)) +} + +/// The answer entries for `ids`, asserting the request succeeded. +async fn ask( + state: &Arc, + tenant: &TenantContext, + viewer: &Keys, + ids: &[Uuid], +) -> Vec { + let (status, body) = ask_with(state, tenant, viewer, ids, true).await; + assert_eq!(status, StatusCode::OK, "{body}"); + body.as_array().expect("answer array").clone() +} + +/// The single entry for `id`, or `None` when it was left out. +async fn ask_one( + state: &Arc, + tenant: &TenantContext, + viewer: &Keys, + id: Uuid, +) -> Option { + let mut answers = ask(state, tenant, viewer, &[id]).await; + assert!(answers.len() <= 1); + answers.pop() +} + +fn entry(id: Uuid, post: bool, joined: bool, role: &str) -> Value { + json!({"id": id, "read": true, "post": post, "joined": joined, "role": role, "archived": false}) +} + +/// `entry` for a channel that is itself archived. +fn archived(mut entry: Value) -> Value { + entry["archived"] = json!(true); + entry +} + +/// One page of the list form: its entries and its `next`. +async fn page( + state: &Arc, + tenant: &TenantContext, + viewer: &Keys, + body: Value, +) -> (Vec, Option) { + let (status, body) = query(state, tenant, viewer, &json!([body]), true).await; + assert_eq!(status, StatusCode::OK, "{body}"); + let entries = body["channels"].as_array().expect("channels").clone(); + let next = match &body["next"] { + Value::Null => None, + next => Some(next.as_str().expect("next id").parse().expect("uuid")), + }; + (entries, next) +} + +/// A private project, a private child under it whose owner made it, and a +/// task in the child with its conversation open. +struct Fixture { + state: Arc, + tenant: TenantContext, + owner: Keys, + project: Uuid, + child: Uuid, + task: Uuid, + task_head: nostr::Event, + conversation: Uuid, +} + +impl Fixture { + async fn new(state: Arc, label: &str) -> Self { + let tenant = community(&state, label).await; + let owner = Keys::generate(); + let project = create_channel(&state, &tenant, &owner, &[&["visibility", "private"]]).await; + let child = create_channel(&state, &tenant, &owner, &[&["visibility", "private"]]).await; + set_parent(&state, &tenant, &owner, child, Some(project)) + .await + .expect("file the child"); + let (task, task_head) = create_task(&state, &tenant, &owner, child).await; + let conversation = open(&state, &tenant, &owner, task) + .await + .expect("open the conversation"); + Self { + state, + tenant, + owner, + project, + child, + task, + task_head, + conversation, + } + } +} + +/// A viewer learns, per named channel, whether they read, post and joined, +/// and the role they act with: from their own row, from the parents, and +/// from an open channel's `join_role`. Unreadable and missing channels are +/// left out, the order is the request's, archiving closes posting, and a +/// conversation follows its home. A proof without a payload tag is refused, +/// and a client cannot send the push itself. +/// Mutation: report every channel as joined, ignore `closed_by_archive`, +/// ignore an open channel's `join_role`, or never report `archived` → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn a_viewer_learns_what_they_may_do_in_each_channel() { + let f = Fixture::new(live_state().await, "access").await; + let (state, tenant) = (&f.state, &f.tenant); + let member = Keys::generate(); + let guest = Keys::generate(); + let outsider = Keys::generate(); + add(state, tenant, &f.owner, f.project, &member, "member").await; + add(state, tenant, &f.owner, f.project, &guest, "guest").await; + let open_channel = create_channel(state, tenant, &f.owner, &[]).await; + edit_channel( + state, + tenant, + &f.owner, + open_channel, + &[&["join_role", "guest"]], + ) + .await + .expect("join as guest"); + let missing = Uuid::new_v4(); + let all = [f.child, missing, f.project, f.conversation, open_channel]; + + assert_eq!( + ask(state, tenant, &f.owner, &all).await, + vec![ + entry(f.child, true, true, "owner"), + entry(f.project, true, true, "owner"), + // A role through parents is capped at member. + entry(f.conversation, true, false, "member"), + entry(open_channel, true, true, "owner"), + ], + "the owner, in request order, without the missing channel" + ); + assert_eq!( + ask(state, tenant, &member, &all).await, + vec![ + entry(f.child, true, false, "member"), + entry(f.project, true, true, "member"), + entry(f.conversation, true, false, "member"), + entry(open_channel, false, false, "guest"), + ], + "a project member reads and posts through the parents" + ); + assert_eq!( + ask(state, tenant, &guest, &all).await, + vec![ + entry(f.child, false, false, "guest"), + entry(f.project, false, true, "guest"), + entry(f.conversation, false, false, "guest"), + entry(open_channel, false, false, "guest"), + ], + "a project guest reads everywhere and posts nowhere" + ); + assert_eq!( + ask(state, tenant, &outsider, &all).await, + vec![entry(open_channel, false, false, "guest")], + "an outsider reads only the open channel" + ); + // The answer agrees with the post gate. + assert!(post(state, tenant, &member, f.conversation).await.is_ok()); + assert!(post(state, tenant, &guest, f.conversation).await.is_err()); + assert!(post(state, tenant, &member, open_channel).await.is_err()); + + edit_channel(state, tenant, &f.owner, f.child, &[&["archived", "true"]]) + .await + .expect("archive the child"); + assert_eq!( + ask(state, tenant, &member, &[f.child, f.conversation]).await, + vec![ + archived(entry(f.child, false, false, "member")), + entry(f.conversation, false, false, "member"), + ], + "an archived home closes itself and its conversation to posts" + ); + assert!(post(state, tenant, &member, f.conversation).await.is_err()); + + let (status, body) = ask_with(state, tenant, &member, &[f.child], false).await; + assert_eq!(status, StatusCode::UNAUTHORIZED, "{body}"); + + let forged = EventBuilder::new(Kind::Custom(KIND_CHANNEL_ACCESS_CHANGED as u16), "") + .tags([Tag::parse(["h", &f.child.to_string()]).unwrap()]) + .sign_with_keys(&member) + .unwrap(); + let refused = send(state, tenant, forged.clone()) + .await + .expect_err("relay-only"); + assert!(refused.contains("relay-only"), "{refused}"); + // Over a WebSocket, where ephemeral kinds skip ingest, too. + let (conn, mut frames) = + crate::handlers::group_state_postgres_tests::test_conn(tenant, &member); + crate::handlers::event::handle_event(forged.clone(), conn, state.clone()).await; + let Message::Text(text) = frames.try_recv().expect("an OK") else { + panic!("expected OK") + }; + let ok: Value = serde_json::from_str(&text).unwrap(); + assert_eq!(ok[0], "OK"); + assert_eq!(ok[1], forged.id.to_hex()); + assert_eq!(ok[2], false); + assert!(ok[3].as_str().unwrap().contains("relay-only"), "{ok}"); +} + +/// Without `ids`, a viewer learns about every channel they can reach, in id +/// order: what they joined, listed open channels, and what those hold. A +/// task conversation and a private channel they can't read stay out, and an +/// archived channel is listed as archived. +/// Mutation: drop the parents' children from the list, or answer the raw +/// list without filtering → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn a_viewer_lists_every_channel_they_can_reach() { + let f = Fixture::new(live_state().await, "reach").await; + let (state, tenant) = (&f.state, &f.tenant); + let member = Keys::generate(); + let outsider = Keys::generate(); + add(state, tenant, &f.owner, f.project, &member, "member").await; + let grandchild = create_channel(state, tenant, &f.owner, &[&["visibility", "private"]]).await; + set_parent(state, tenant, &f.owner, grandchild, Some(f.child)) + .await + .expect("file the grandchild"); + let walled = create_channel(state, tenant, &f.owner, &[&["visibility", "private"]]).await; + set_parent(state, tenant, &f.owner, walled, Some(f.project)) + .await + .expect("file the walled channel"); + edit_channel( + state, + tenant, + &f.owner, + walled, + &[&["parent_access", "none"]], + ) + .await + .expect("wall it off"); + let open_channel = create_channel(state, tenant, &f.owner, &[]).await; + edit_channel( + state, + tenant, + &f.owner, + open_channel, + &[&["join_role", "guest"]], + ) + .await + .expect("join as guest"); + edit_channel( + state, + tenant, + &f.owner, + grandchild, + &[&["archived", "true"]], + ) + .await + .expect("archive the grandchild"); + let reach = |viewer: &Keys| { + let viewer = viewer.clone(); + async move { + let (entries, next) = page(state, tenant, &viewer, json!({"access": "channels"})).await; + assert_eq!(next, None, "one page holds them all"); + entries + } + }; + let sorted = |mut entries: Vec| { + entries.sort_by_key(|e| e["id"].as_str().unwrap().to_string()); + entries + }; + + assert_eq!( + reach(&member).await, + sorted(vec![ + entry(f.project, true, true, "member"), + entry(f.child, true, false, "member"), + archived(entry(grandchild, false, false, "member")), + entry(open_channel, false, false, "guest"), + ]), + "a project member reaches its tree and the open channel, not the conversation or the walled channel" + ); + assert_eq!( + reach(&outsider).await, + vec![entry(open_channel, false, false, "guest")], + "an outsider reaches only the open channel" + ); + let (status, body) = query( + state, + tenant, + &member, + &json!([{"access": "channels"}]), + false, + ) + .await; + assert_eq!(status, StatusCode::UNAUTHORIZED, "{body}"); +} + +/// Register a connection for `viewer` subscribed to the push in `channels`; +/// its ID and frame receiver. +fn subscribe( + state: &Arc, + tenant: &TenantContext, + viewer: &Keys, + channels: &[Uuid], +) -> (Uuid, tokio::sync::mpsc::Receiver) { + let conn_id = Uuid::new_v4(); + let (tx, rx) = tokio::sync::mpsc::channel(32); + state.conn_manager.register( + conn_id, + tx, + tokio::sync::mpsc::channel(4).0, + tokio::sync::mpsc::channel(1).0, + None, + tokio_util::sync::CancellationToken::new(), + tenant.community(), + Arc::new(std::sync::atomic::AtomicU8::new(0)), + Arc::new(tokio::sync::Mutex::new(Default::default())), + 3, + crate::state::CommunityConnectionControl::new(tokio_util::sync::CancellationToken::new()), + ); + state + .conn_manager + .set_authenticated_pubkey(conn_id, viewer.public_key().to_bytes().to_vec()); + for &channel in channels { + let filter = json!({"kinds": [9, KIND_CHANNEL_ACCESS_CHANGED], "#h": [channel]}); + state.sub_registry.register_scoped( + tenant.community(), + conn_id, + format!("chan-{channel}"), + vec![serde_json::from_value(filter).expect("filter")], + Some(channel), + ); + } + (conn_id, rx) +} + +fn subscribed(state: &AppState, tenant: &TenantContext, channel: Uuid, conn_id: Uuid) -> bool { + state + .sub_registry + .channel_subscriber_conns_scoped(tenant.community(), channel) + .contains(&conn_id) +} + +/// The channels named by the relay-signed pushes in `rx` within `wait`. +async fn pushes( + state: &AppState, + rx: &mut tokio::sync::mpsc::Receiver, + wait: Duration, +) -> Vec { + let mut channels = Vec::new(); + let deadline = tokio::time::Instant::now() + wait; + while let Ok(Some(frame)) = tokio::time::timeout_at(deadline, rx.recv()).await { + let Message::Text(text) = frame else { continue }; + let frame: Value = serde_json::from_str(&text).expect("frame"); + if frame[0] != "EVENT" { + continue; + } + let event: nostr::Event = serde_json::from_value(frame[2].clone()).expect("event"); + if event.kind != Kind::Custom(KIND_CHANNEL_ACCESS_CHANGED as u16) { + continue; + } + assert_eq!( + event.pubkey, + state.relay_keypair.public_key(), + "relay-signed" + ); + assert!(event.content.is_empty()); + event.verify().expect("valid signature"); + let tags: Vec> = event.tags.iter().map(|t| t.clone().to_vec()).collect(); + assert_eq!(tags.len(), 1, "only the h tag: {tags:?}"); + assert_eq!(tags[0][0], "h"); + channels.push(tags[0][1].parse().expect("channel id")); + } + channels +} + +/// A state with live Redis at `REDIS_URL` and multi-node fan-out: `POST +/// /query` admission and the push both go through Redis. +pub(crate) async fn live_state() -> Arc { + let redis_url = std::env::var("REDIS_URL").expect("REDIS_URL names a live Redis"); + let state = crate::state::tests::test_state_with_database_and_redis_url( + &crate::test_support::database_url(), + &redis_url, + ) + .await; + tokio::spawn(state.pubsub.clone().run_subscriber()); + crate::handlers::multinode_fanout::spawn(state.clone(), state.pubsub.subscribe_local()); + state +} + +/// Listen for Redis topics of `channels` on `state`, as a subscribing +/// client's REQ does. +async fn retain(state: &AppState, tenant: &TenantContext, channels: &[Uuid]) { + for &channel in channels { + state + .pubsub + .retain_topic(tenant, buzz_pubsub::EventTopic::Channel(channel)) + .await; + } + tokio::time::sleep(Duration::from_millis(300)).await; +} + +/// A project guest has a task's conversation open. Made a member of the +/// project, they are told to ask again in the project, the child and the +/// conversation, the answer now lets them post, and they stay subscribed +/// throughout. Removed from the project, the other subscribers are told, and +/// the removed person's subscriptions close and the answer leaves them out. +/// Mutation: drop the push from the kind:9000 path, or the descendants from +/// `announce_changed` → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn an_upgraded_guest_is_told_to_ask_again_and_stays_subscribed() { + let state = live_state().await; + let f = Fixture::new(state, "access-push").await; + let (state, tenant) = (&f.state, &f.tenant); + let guest = Keys::generate(); + add(state, tenant, &f.owner, f.project, &guest, "guest").await; + let channels = [f.project, f.child, f.conversation]; + retain(state, tenant, &channels).await; + let (guest_conn, mut guest_rx) = subscribe(state, tenant, &guest, &channels); + let (_owner_conn, mut owner_rx) = subscribe(state, tenant, &f.owner, &[f.conversation]); + assert_eq!( + ask_one(state, tenant, &guest, f.conversation).await, + Some(entry(f.conversation, false, false, "guest")) + ); + + add(state, tenant, &f.owner, f.project, &guest, "member").await; + let mut told = pushes(state, &mut guest_rx, Duration::from_secs(3)).await; + told.sort(); + let mut expected = channels.to_vec(); + expected.sort(); + assert_eq!(told, expected, "told once in each channel it reads"); + assert_eq!( + ask_one(state, tenant, &guest, f.conversation).await, + Some(entry(f.conversation, true, false, "member")), + "the answer now lets them post" + ); + for channel in channels { + assert!( + subscribed(state, tenant, channel, guest_conn), + "still subscribed" + ); + } + assert_eq!( + pushes(state, &mut owner_rx, Duration::from_millis(500)).await, + vec![f.conversation], + "everyone reading the conversation is told" + ); + + let remove = EventBuilder::new(Kind::Custom(9001), "") + .tags([ + Tag::parse(["h", &f.project.to_string()]).unwrap(), + Tag::parse(["p", &guest.public_key().to_hex()]).unwrap(), + ]) + .sign_with_keys(&f.owner) + .unwrap(); + let result = crate::handlers::ingest::ingest_event( + state, + tenant, + remove, + crate::handlers::group_state_postgres_tests::http_auth(&f.owner), + ) + .await + .expect("remove"); + assert!(result.accepted, "{:?}", result.message); + assert_eq!( + pushes(state, &mut owner_rx, Duration::from_secs(3)).await, + vec![f.conversation], + "the remaining readers are told" + ); + for channel in channels { + assert!( + !subscribed(state, tenant, channel, guest_conn), + "revoked: {channel}" + ); + } + assert!(ask(state, tenant, &guest, &channels).await.is_empty()); +} + +/// Archiving a home and moving a task tell the conversation's subscribers +/// to ask again; a change that leaves access alone does not. +/// Mutation: drop the push from the kind:9002 path or from +/// `artifact_conversation_access_changed` → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn archiving_and_moving_tell_the_conversation_to_ask_again() { + let state = live_state().await; + let f = Fixture::new(state, "access-archive").await; + let (state, tenant) = (&f.state, &f.tenant); + retain(state, tenant, &[f.conversation]).await; + let (_conn, mut rx) = subscribe(state, tenant, &f.owner, &[f.conversation]); + + edit_channel(state, tenant, &f.owner, f.child, &[&["archived", "true"]]) + .await + .expect("archive"); + assert_eq!( + pushes(state, &mut rx, Duration::from_secs(3)).await, + vec![f.conversation] + ); + edit_channel(state, tenant, &f.owner, f.child, &[&["archived", "false"]]) + .await + .expect("unarchive"); + assert_eq!( + pushes(state, &mut rx, Duration::from_secs(3)).await, + vec![f.conversation] + ); + edit_channel(state, tenant, &f.owner, f.child, &[&["about", "renamed"]]) + .await + .expect("describe"); + assert!( + pushes(state, &mut rx, Duration::from_millis(500)) + .await + .is_empty(), + "a change that leaves access alone is not announced" + ); + + let other = create_channel(state, tenant, &f.owner, &[&["visibility", "private"]]).await; + let moved = task(&f.owner, other, f.task, "move", Some(&f.task_head)); + send(state, tenant, moved).await.expect("move the task"); + assert_eq!( + pushes(state, &mut rx, Duration::from_secs(3)).await, + vec![f.conversation] + ); +} + +/// Joining and leaving tell the channel's subscribers, and those of the +/// private channels under it, to ask again. +/// Mutation: drop the push from the kind:9021 or kind:9022 path → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn joining_and_leaving_are_announced() { + let state = live_state().await; + let f = Fixture::new(state, "access-join").await; + let (state, tenant) = (&f.state, &f.tenant); + let person = Keys::generate(); + add(state, tenant, &f.owner, f.project, &person, "member").await; + let open_channel = create_channel(state, tenant, &f.owner, &[]).await; + retain(state, tenant, &[f.conversation, open_channel]).await; + let (_conn, mut rx) = subscribe(state, tenant, &f.owner, &[f.conversation, open_channel]); + + let join = EventBuilder::new(Kind::Custom(9021), "") + .tags([Tag::parse(["h", &open_channel.to_string()]).unwrap()]) + .sign_with_keys(&person) + .unwrap(); + send(state, tenant, join).await.expect("join"); + assert_eq!( + pushes(state, &mut rx, Duration::from_secs(3)).await, + vec![open_channel] + ); + + let leave = EventBuilder::new(Kind::Custom(9022), "") + .tags([Tag::parse(["h", &f.project.to_string()]).unwrap()]) + .sign_with_keys(&person) + .unwrap(); + send(state, tenant, leave).await.expect("leave"); + assert_eq!( + pushes(state, &mut rx, Duration::from_secs(3)).await, + vec![f.conversation] + ); +} + +/// Walking the list form page by page, a viewer who can reach more than 500 +/// channels gets each exactly once and in id order, at the default page +/// size and at a small one, and the last page says there are no more. +/// Mutation: start a page at `after` inclusive, or end the walk at a fixed +/// count → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn a_viewer_walks_every_reachable_channel_page_by_page() { + let state = live_state().await; + let tenant = community(&state, "access-pages").await; + let owner = Keys::generate(); + let viewer = Keys::generate(); + let mut made = Vec::new(); + for _ in 0..523 { + made.push(create_channel(&state, &tenant, &owner, &[]).await); + } + made.sort(); + + for limit in [None, Some(37)] { + let mut seen = Vec::new(); + let mut after: Option = None; + let mut pages = 0; + loop { + let mut body = json!({"access": "channels"}); + if let Some(after) = after { + body["after"] = json!(after); + } + if let Some(limit) = limit { + body["limit"] = json!(limit); + } + let (entries, next) = page(&state, &tenant, &viewer, body).await; + assert!(entries.len() <= limit.unwrap_or(100)); + seen.extend( + entries + .iter() + .map(|e| e["id"].as_str().unwrap().parse::().unwrap()), + ); + pages += 1; + match next { + Some(next) => after = Some(next), + None => break, + } + } + assert_eq!(seen, made, "each channel once, in id order ({limit:?})"); + assert_eq!(pages, 523usize.div_ceil(limit.unwrap_or(100)), "{limit:?}"); + } +} + +/// A full page under nested projects answers well inside the deadline: +/// 100 private grandchildren, each read through two levels of parents. +/// Mutation: make each answer wait 100ms → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn a_full_page_under_nested_projects_answers_quickly() { + let state = live_state().await; + let tenant = community(&state, "access-cost").await; + let owner = Keys::generate(); + let member = Keys::generate(); + let private: &[&[&str]] = &[&["visibility", "private"]]; + let project = create_channel(&state, &tenant, &owner, private).await; + add(&state, &tenant, &owner, project, &member, "member").await; + let mut grandchildren = Vec::new(); + for _ in 0..10 { + let child = create_channel(&state, &tenant, &owner, private).await; + set_parent(&state, &tenant, &owner, child, Some(project)) + .await + .expect("file the child"); + for _ in 0..10 { + let grandchild = create_channel(&state, &tenant, &owner, private).await; + set_parent(&state, &tenant, &owner, grandchild, Some(child)) + .await + .expect("file the grandchild"); + grandchildren.push(grandchild); + } + } + + let started = std::time::Instant::now(); + let answers = ask(&state, &tenant, &member, &grandchildren).await; + let named = started.elapsed(); + assert_eq!(answers.len(), 100); + assert!(answers + .iter() + .all(|a| a["post"] == true && a["role"] == "member")); + + let started = std::time::Instant::now(); + let (entries, next) = page(&state, &tenant, &member, json!({"access": "channels"})).await; + let listed = started.elapsed(); + assert_eq!(entries.len(), 100, "a full page of the 111 reachable"); + assert!(next.is_some()); + + let budget = Duration::from_secs(2); + assert!(named < budget, "named form took {named:?}"); + assert!(listed < budget, "list form took {listed:?}"); +} + +/// Listen on `viewer`'s connection for the relay's per-viewer push, as a +/// client's `{"kinds":[20005],"#p":[]}` REQ does. With `p` false the +/// filter names no `#p`, as a REQ the relay would refuse; fan-out must still +/// deliver nothing that names someone else. +pub(crate) fn subscribe_viewer( + state: &Arc, + tenant: &TenantContext, + viewer: &Keys, + p: bool, +) -> tokio::sync::mpsc::Receiver { + let (conn_id, rx) = subscribe(state, tenant, viewer, &[]); + let filter = if p { + json!({"kinds": [KIND_VIEWER_ACCESS_CHANGED], "#p": [viewer.public_key().to_hex()]}) + } else { + json!({"kinds": [KIND_VIEWER_ACCESS_CHANGED]}) + }; + state.sub_registry.register_scoped( + tenant.community(), + conn_id, + "viewer".to_string(), + vec![serde_json::from_value(filter).expect("filter")], + None, + ); + rx +} + +/// The pubkeys named by relay-signed per-viewer pushes in `rx` within `wait`. +pub(crate) async fn viewer_pushes( + state: &AppState, + rx: &mut tokio::sync::mpsc::Receiver, + wait: Duration, +) -> Vec { + let mut named = Vec::new(); + let deadline = tokio::time::Instant::now() + wait; + while let Ok(Some(frame)) = tokio::time::timeout_at(deadline, rx.recv()).await { + let Message::Text(text) = frame else { continue }; + let frame: Value = serde_json::from_str(&text).expect("frame"); + if frame[0] != "EVENT" { + continue; + } + let event: nostr::Event = serde_json::from_value(frame[2].clone()).expect("event"); + if event.kind != Kind::Custom(KIND_VIEWER_ACCESS_CHANGED as u16) { + continue; + } + assert_eq!(event.pubkey, state.relay_keypair.public_key()); + assert!(event.content.is_empty()); + event.verify().expect("valid signature"); + let tags: Vec> = event.tags.iter().map(|t| t.clone().to_vec()).collect(); + assert_eq!(tags.len(), 1, "only the p tag: {tags:?}"); + assert_eq!(tags[0][0], "p"); + named.push(tags[0][1].clone()); + } + named +} + +/// Apply a moderation command signed by `actor` against `target`. +async fn moderate( + state: &Arc, + tenant: &TenantContext, + actor: &Keys, + kind: u32, + target: &Keys, + until: Option, +) { + let mut tags = vec![Tag::public_key(target.public_key())]; + if let Some(until) = until { + tags.push(Tag::parse(["expiration", &until.to_string()]).unwrap()); + } + let event = EventBuilder::new(Kind::Custom(kind as u16), "") + .tags(tags) + .sign_with_keys(actor) + .unwrap(); + crate::handlers::moderation_commands::handle_moderation_command(tenant, state, &event) + .await + .unwrap_or_else(|e| panic!("kind {kind} must apply: {e:?}")); +} + +/// A timed-out person, and an agent they own, are told they may not post +/// anywhere and until when, matching the post gate. The timeout and its +/// lifting are each pushed to that person and their agent, and to no one +/// else. A timeout that runs out lifts on time with no push: the answer's +/// `timed_out_until` is when to ask again. A ban is pushed too, and the +/// banned person and their agent are then refused with the reason. +/// Mutation: leave the restriction out of `post`, drop `timed_out_until`, +/// drop the push from `restrictions_changed`, skip the owner's agents, or +/// deliver the push without the p gate → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn a_timeout_closes_posting_and_is_pushed_to_that_person_only() { + let f = Fixture::new(live_state().await, "access-timeout").await; + let (state, tenant) = (&f.state, &f.tenant); + let (member, agent, bystander) = (Keys::generate(), Keys::generate(), Keys::generate()); + for (keys, role) in [ + (&f.owner, "owner"), + (&member, "member"), + (&bystander, "member"), + ] { + state + .db + .add_relay_member( + tenant.community(), + &keys.public_key().to_hex(), + role, + None, + &Keys::generate(), + ) + .await + .map(|write| write.outcome) + .expect("relay member"); + } + for keys in [&member, &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(), + member.public_key().as_bytes(), + ) + .await + .expect("own the agent")); + for keys in [&member, &agent] { + add(state, tenant, &f.owner, f.project, keys, "member").await; + } + state + .pubsub + .retain_topic(tenant, buzz_pubsub::EventTopic::Global) + .await; + tokio::time::sleep(Duration::from_millis(300)).await; + let mut member_rx = subscribe_viewer(state, tenant, &member, true); + let mut agent_rx = subscribe_viewer(state, tenant, &agent, true); + let mut snoop_rx = subscribe_viewer(state, tenant, &bystander, false); + let channels = [f.project, f.child, f.conversation]; + let open_to_post = |id| entry(id, true, id == f.project, "member"); + for keys in [&member, &agent] { + assert_eq!( + ask(state, tenant, keys, &channels).await, + channels.map(open_to_post).to_vec() + ); + } + + let until = (chrono::Utc::now() + chrono::Duration::hours(1)).timestamp(); + moderate( + state, + tenant, + &f.owner, + buzz_core::kind::KIND_MODERATION_TIMEOUT, + &member, + Some(until), + ) + .await; + let member_hex = member.public_key().to_hex(); + let agent_hex = agent.public_key().to_hex(); + assert_eq!( + viewer_pushes(state, &mut member_rx, Duration::from_secs(3)).await, + vec![member_hex.clone()] + ); + assert_eq!( + viewer_pushes(state, &mut agent_rx, Duration::from_secs(1)).await, + vec![agent_hex.clone()] + ); + assert!( + viewer_pushes(state, &mut snoop_rx, Duration::from_millis(500)) + .await + .is_empty(), + "no one else learns of the timeout" + ); + for keys in [&member, &agent] { + let closed: Vec = channels + .map(|id| { + let mut e = entry(id, false, id == f.project, "member"); + e["timed_out_until"] = json!(until); + e + }) + .to_vec(); + assert_eq!(ask(state, tenant, keys, &channels).await, closed); + assert!(post(state, tenant, keys, f.child).await.is_err()); + } + + moderate( + state, + tenant, + &f.owner, + buzz_core::kind::KIND_MODERATION_UNTIMEOUT, + &member, + None, + ) + .await; + assert_eq!( + viewer_pushes(state, &mut member_rx, Duration::from_secs(3)).await, + vec![member_hex.clone()] + ); + assert_eq!( + viewer_pushes(state, &mut agent_rx, Duration::from_secs(1)).await, + vec![agent_hex] + ); + assert!( + viewer_pushes(state, &mut snoop_rx, Duration::from_millis(500)) + .await + .is_empty() + ); + for keys in [&member, &agent] { + assert_eq!( + ask(state, tenant, keys, &channels).await, + channels.map(open_to_post).to_vec() + ); + assert!(post(state, tenant, keys, f.child).await.is_ok()); + } + + // A short timeout lifts on its own, and the answer follows the clock. + let soon = chrono::Utc::now().timestamp() + 3; + moderate( + state, + tenant, + &f.owner, + buzz_core::kind::KIND_MODERATION_TIMEOUT, + &member, + Some(soon), + ) + .await; + let entry = ask_one(state, tenant, &member, f.child).await.unwrap(); + assert_eq!( + (entry["post"].clone(), entry["timed_out_until"].clone()), + (json!(false), json!(soon)) + ); + tokio::time::sleep(Duration::from_millis( + u64::try_from(soon * 1000 - chrono::Utc::now().timestamp_millis()).unwrap_or(0) + 500, + )) + .await; + assert_eq!( + ask_one(state, tenant, &member, f.child).await, + Some(open_to_post(f.child)) + ); + assert!(post(state, tenant, &member, f.child).await.is_ok()); + assert_eq!( + viewer_pushes(state, &mut member_rx, Duration::from_millis(200)).await, + vec![member_hex.clone()], + "the short timeout is pushed when set, and not when it runs out" + ); + + // A banned person is told they may not post, with no end to wait for, + // even under a timeout that has one. + moderate( + state, + tenant, + &f.owner, + buzz_core::kind::KIND_MODERATION_TIMEOUT, + &member, + Some(until), + ) + .await; + moderate( + state, + tenant, + &f.owner, + buzz_core::kind::KIND_MODERATION_BAN, + &member, + None, + ) + .await; + assert!(viewer_pushes(state, &mut member_rx, Duration::from_secs(3)) + .await + .contains(&member.public_key().to_hex())); + // A banned person, and the agent restricted through them, are refused + // outright with the reason, as every HTTP request from them is. + for keys in [&member, &agent] { + let (status, refused) = ask_with(state, tenant, keys, &[f.child], true).await; + assert_eq!(status, StatusCode::FORBIDDEN, "{refused}"); + assert!( + refused["error"] + .as_str() + .is_some_and(|e| e.contains("banned")), + "{refused}" + ); + assert!(post(state, tenant, keys, f.child).await.is_err()); + } +} diff --git a/crates/buzz-relay/src/handlers/event.rs b/crates/buzz-relay/src/handlers/event.rs index 504e79b735d..75bba376ba3 100644 --- a/crates/buzz-relay/src/handlers/event.rs +++ b/crates/buzz-relay/src/handlers/event.rs @@ -7,8 +7,9 @@ use tracing::{debug, error, info, warn}; use buzz_core::event::StoredEvent; use buzz_core::kind::{ - 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, + event_kind_u32, is_ephemeral, is_relay_only_kind, 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, @@ -777,6 +778,14 @@ pub async fn handle_event(event: Event, conn: Arc, state: Arc Result { + if channel.archived_at.is_some() { + return Ok(true); + } + match channel.parent_id { + Some(home) if channel.channel_type == buzz_db::channel::ChannelType::Artifact.as_str() => { + match state + .db + .get_channel_for_event_write(community_id, home) + .await + { + Ok(home) => Ok(home.archived_at.is_some()), + Err(buzz_db::DbError::ChannelNotFound(_)) => Ok(false), + Err(e) => Err(e), + } + } + _ => Ok(false), + } +} + /// The role-table write rule, for an actor that already passed the /// read/membership gate of `channel`. /// @@ -2412,7 +2438,7 @@ fn allowed_while_timed_out(kind: u32) -> bool { } /// The write-path verdict for a restriction snapshot, or `None` to admit. -fn write_restriction_denial( +pub(crate) fn write_restriction_denial( kind: u32, restriction: &buzz_db::moderation::RestrictionState, now: chrono::DateTime, @@ -3190,19 +3216,10 @@ async fn ingest_event_inner( if !is_edit_metadata && !is_self_departure { if let Some(channel) = &channel_row { - // An artifact's conversation is archived with its home. - let home_archived = match channel.parent_id { - Some(home) - if channel.channel_type - == buzz_db::channel::ChannelType::Artifact.as_str() => - { - load_channel_for_write(tenant, state, home) - .await? - .is_some_and(|home| home.archived_at.is_some()) - } - _ => false, - }; - if channel.archived_at.is_some() || home_archived { + let archived = closed_by_archive(tenant.community(), state, channel) + .await + .map_err(|e| IngestError::Internal(format!("error: database error: {e}")))?; + if archived { return Err(match target_denial { Some(reason) => target_denied(reason), None => IngestError::Rejected("invalid: channel is archived".into()), diff --git a/crates/buzz-relay/src/handlers/mod.rs b/crates/buzz-relay/src/handlers/mod.rs index 78bf485f738..78606f6b36e 100644 --- a/crates/buzz-relay/src/handlers/mod.rs +++ b/crates/buzz-relay/src/handlers/mod.rs @@ -2,12 +2,16 @@ pub mod admin_action_worker; pub mod admin_outbox_worker; #[cfg(test)] -mod artifact_conversation_postgres_tests; +pub(crate) mod artifact_conversation_postgres_tests; /// NIP-AR Sync subscriptions. pub mod artifact_sync; #[cfg(test)] mod artifact_sync_postgres_tests; pub mod auth; +/// What a viewer may do in named channels, and the push to ask again. +pub mod channel_access; +#[cfg(test)] +pub(crate) mod channel_access_postgres_tests; /// Pure NIP-29 channel membership-authority decisions (kinds 9000/9001/9022). pub mod channel_authz; /// Subscription close (CLOSE) handler. diff --git a/crates/buzz-relay/src/handlers/moderation_commands.rs b/crates/buzz-relay/src/handlers/moderation_commands.rs index 65897bdd6f2..bc055cfebeb 100644 --- a/crates/buzz-relay/src/handlers/moderation_commands.rs +++ b/crates/buzz-relay/src/handlers/moderation_commands.rs @@ -200,7 +200,7 @@ async fn handle_ban( ) .await .map_err(|e| error(format!("database error: {e}")))?; - state.invalidate_restrictions(tenant); + state.restrictions_changed(tenant, Some(&target)); // Live enforcement: close open sessions for the banned principal now — // this pod's sockets synchronously (fenced to this community) and every @@ -286,7 +286,7 @@ async fn handle_unban( if !lifted { return Err(invalid("member is not banned")); } - state.invalidate_restrictions(tenant); + state.restrictions_changed(tenant, Some(&target)); insert_audit(state, tenant, actor, "unban", Some(&target), None, None).await?; @@ -329,7 +329,7 @@ async fn handle_timeout( ) .await .map_err(|e| error(format!("database error: {e}")))?; - state.invalidate_restrictions(tenant); + state.restrictions_changed(tenant, Some(&target)); let action_id = insert_audit( state, @@ -393,7 +393,7 @@ async fn handle_untimeout( if !cleared { return Err(invalid("member is not timed out")); } - state.invalidate_restrictions(tenant); + state.restrictions_changed(tenant, Some(&target)); insert_audit(state, tenant, actor, "untimeout", Some(&target), None, None).await?; diff --git a/crates/buzz-relay/src/handlers/report_resolution.rs b/crates/buzz-relay/src/handlers/report_resolution.rs index c04ec08c8f7..1f74d2be118 100644 --- a/crates/buzz-relay/src/handlers/report_resolution.rs +++ b/crates/buzz-relay/src/handlers/report_resolution.rs @@ -670,7 +670,10 @@ async fn drive_enforcement( // The restriction row changed: drop the community's cached rows on // every pod. On every convergence path, so recovery repeats it. if matches!(action, "ban" | "timeout") { - state.invalidate_restrictions(tenant); + state.restrictions_changed( + tenant, + target_pubkey.or(rec.enforcement_target_pubkey.as_deref()), + ); } // A ban closes the target's open sessions clusterwide, matching the // in-community kind-9040 ban. It runs before finalize so a crash in diff --git a/crates/buzz-relay/src/handlers/side_effects.rs b/crates/buzz-relay/src/handlers/side_effects.rs index add9e9ed8de..e7b227be643 100644 --- a/crates/buzz-relay/src/handlers/side_effects.rs +++ b/crates/buzz-relay/src/handlers/side_effects.rs @@ -161,6 +161,7 @@ pub(crate) async fn apply_kick_live_side_effects( } // The fence is released, so the channels under this one can be read. evict_departed_descendant_reader(tenant, state, channel_id, target_pubkey).await; + super::channel_access::announce_changed(tenant, state, channel_id); // The removal is committed: refresh the channel's discovery roster, then // tell the kicked member, as a kind:9001 removal does. The notice tells a @@ -355,6 +356,7 @@ pub(crate) async fn artifact_conversation_access_changed( if let Err(e) = evict_non_reader_channel_subscriptions(tenant, state, conversation).await { warn!(channel = %conversation, error = %e, "non-reader subscription eviction failed"); } + super::channel_access::announce_changed(tenant, state, conversation); } async fn evict_non_reader_channel_subscriptions( @@ -2441,6 +2443,9 @@ pub(crate) async fn persist_put_user( warn!(channel = %channel_id, error = %e, "NIP-29 group discovery emission failed"); } } + if !report.added.is_empty() || !report.updated.is_empty() { + super::channel_access::announce_changed(tenant, state, channel_id); + } info!( channel = %channel_id, @@ -2496,6 +2501,7 @@ pub(crate) async fn persist_remove_user( evict_live_channel_subscriptions(tenant, state, channel_id, &target_pubkey).await; evict_departed_descendant_reader(tenant, state, channel_id, &target_pubkey).await; disable_departed_member_workflows(tenant, state, channel_id, &target_pubkey).await; + super::channel_access::announce_changed(tenant, state, channel_id); let actor_hex = hex::encode(&actor_bytes); let target_hex = hex::encode(&target_pubkey); @@ -2694,6 +2700,11 @@ pub(crate) async fn persist_edit_metadata( let unlisted_changed = edit.columns.unlisted.is_some(); let parent_changed = edit.columns.parent_id.is_some() || edit.columns.parent_access.is_some(); let unarchived = edit.archived == Some(false); + // What the channel access answer reads: who may read and who may post. + let access_changed = new_visibility.is_some() + || parent_changed + || edit.archived.is_some() + || edit.columns.join_role.is_some(); let write = state .db .apply_channel_metadata_event( @@ -2751,6 +2762,9 @@ pub(crate) async fn persist_edit_metadata( for message in &system_messages { fan_out_system_message(tenant, state, channel_id, message).await; } + if access_changed { + super::channel_access::announce_changed(tenant, state, channel_id); + } if unarchived { resubscribe_members_after_unarchive(tenant, state, channel_id, &actor_bytes).await; } @@ -3140,6 +3154,7 @@ async fn handle_delete_group( // Deleted channel: clear both membership and accessible-channels caches. // Stale is_member=true entries would bypass the DB's deleted_at guard. state.invalidate_channel_deleted(tenant); + super::channel_access::announce_changed(tenant, state, channel_id); // Notify every member only after the delete and discovery cleanup, so a // client that re-reads on the notice no longer sees the channel. The @@ -3254,6 +3269,7 @@ async fn announce_self_join( pubkey: &[u8], ) -> anyhow::Result<()> { state.invalidate_membership(tenant, channel_id, pubkey); + super::channel_access::announce_changed(tenant, state, channel_id); let actor_hex = hex::encode(pubkey); emit_system_message( @@ -3537,6 +3553,7 @@ async fn handle_leave_request( evict_live_channel_subscriptions(tenant, state, channel_id, &actor_bytes).await; evict_departed_descendant_reader(tenant, state, channel_id, &actor_bytes).await; disable_departed_member_workflows(tenant, state, channel_id, &actor_bytes).await; + super::channel_access::announce_changed(tenant, state, channel_id); let actor_hex = hex::encode(&actor_bytes); emit_system_message( diff --git a/crates/buzz-relay/src/main.rs b/crates/buzz-relay/src/main.rs index 3d233bc25c9..8d005c391ba 100644 --- a/crates/buzz-relay/src/main.rs +++ b/crates/buzz-relay/src/main.rs @@ -1085,6 +1085,13 @@ async fn run_relay_main(boot: BootTracker) -> anyhow::Result<()> { // archived channel immediately (CLOSED is in the client's // drop-set → no reconnect storm). Offline clients are caught // by the archived=true skip in discover_channels on reconnect. + // Its subscribers, and those of conversations under it, + // which close to posts with it, ask again. + buzz_relay::handlers::channel_access::announce_changed( + &tenant, + &reaper_state, + channel_id, + ); buzz_relay::handlers::side_effects::evict_all_channel_subscriptions( &tenant, &reaper_state, diff --git a/crates/buzz-relay/src/nip11.rs b/crates/buzz-relay/src/nip11.rs index cd20494f04f..76f4796326d 100644 --- a/crates/buzz-relay/src/nip11.rs +++ b/crates/buzz-relay/src/nip11.rs @@ -277,6 +277,12 @@ impl RelayInfo { // conversation (NOSTR.md, Artifact conversations), and task // sync includes auto-archiving channels. "buzz-artifact-conversations".to_string(), + // `POST /query` answers `{"access":"channels"}` with what the + // signer may do in each named channel or one page of those it + // can reach; kind:20004 tells a channel's live subscribers, and + // kind:20005 one timed-out pubkey, to ask again (NOSTR.md, + // Channel access). + "buzz-channel-access".to_string(), ]; let gif = gif_provider.map(|provider| { supported_extensions.push("buzz-gif".to_string()); @@ -849,6 +855,7 @@ mod tests { assert!(extensions.contains(&"buzz-channel-parents".to_string())); 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())); } /// NIP-WP → NIP-11 mirror: a set workspace icon is served in the standard diff --git a/crates/buzz-relay/src/state.rs b/crates/buzz-relay/src/state.rs index 361cf6d3715..8a4be2d3e05 100644 --- a/crates/buzz-relay/src/state.rs +++ b/crates/buzz-relay/src/state.rs @@ -2106,17 +2106,25 @@ impl AppState { .await } - /// Drop the community's cached restriction rows on this pod and, best - /// effort, on every other pod. Call after every ban, unban, timeout or - /// untimeout write commits, and after an agent's owner is recorded. + /// The one step after a restriction of `target` changes: every ban, + /// unban, timeout or untimeout write, by any route, once it commits, and + /// an agent's owner being recorded. Drops the community's cached + /// restriction rows on this pod and, best effort, on every other pod, + /// then tells `target` and the agents it owns to ask again what they may + /// do ([`crate::handlers::channel_access::announce_restriction_changed`]). + /// `target` is `None` only for a recovered legacy report action that + /// recorded no target. /// /// The drop is community-wide because an agent's row also carries its /// owner's restriction, and the cache does not know which agents a /// target owns. Restriction writes are rare next to the reads this cache /// absorbs, so the refill is cheap. - pub fn invalidate_restrictions(&self, tenant: &TenantContext) { + pub fn restrictions_changed(&self, tenant: &TenantContext, target: Option<&[u8]>) { self.invalidate_restrictions_local(tenant.community()); self.spawn_cache_invalidation(tenant, CacheInvalidation::Restrictions); + if let Some(target) = target { + crate::handlers::channel_access::announce_restriction_changed(tenant, self, target); + } } /// Local-only restriction drop. See [`Self::invalidate_membership_local`]. @@ -2391,13 +2399,13 @@ impl AppState { /// /// The agent's cached restriction row predates the link and lacks the /// owner's restriction, so the community's rows are dropped too (see - /// [`Self::invalidate_restrictions`]). + /// [`Self::restrictions_changed`]). pub fn disconnect_unowned_agent_clusterwide( &self, tenant: &TenantContext, agent: &[u8], ) -> usize { - self.invalidate_restrictions(tenant); + self.restrictions_changed(tenant, Some(agent)); self.disconnect_clusterwide( tenant, agent, @@ -3619,6 +3627,21 @@ pub(crate) mod tests { build_test_state(config, pool).await } + /// [`test_state_with_database_url_and_pool_options`] with a live Redis + /// at `redis_url`, for tests that publish and fan out through it. + pub(crate) async fn test_state_with_database_and_redis_url( + database_url: &str, + redis_url: &str, + ) -> Arc { + let mut config = crate::config::Config::for_test(); + config.require_relay_membership = false; + config.redis_url = redis_url.to_owned(); + config.database_url = database_url.to_owned(); + config.read_database_url = None; + let pool = sqlx::PgPool::connect_lazy(&config.database_url).expect("lazy pg pool"); + build_test_state(config, pool).await + } + /// Build test state around a caller-owned writer pool. Production-path /// lifecycle tests use this to hold the sole connection as a deterministic /// barrier while AUTH waits in the real database acquisition path. @@ -5430,7 +5453,7 @@ pub(crate) mod tests { let cached = |key| state.restriction_cache.entry(&key).is_some(); for invalidate in [ - &(|| state.invalidate_restrictions(&tenant)) as &dyn Fn(), + &(|| state.restrictions_changed(&tenant, Some(&owner))) as &dyn Fn(), &|| state.apply_cache_invalidation(community, CacheInvalidation::Restrictions), ] { seed();