diff --git a/crates/buzz-relay/src/api/mod.rs b/crates/buzz-relay/src/api/mod.rs index b0641a09ce..6c5d78f7f8 100644 --- a/crates/buzz-relay/src/api/mod.rs +++ b/crates/buzz-relay/src/api/mod.rs @@ -645,6 +645,10 @@ pub mod relay_members { state .author_type_cache .insert((tenant.community(), agent.to_bytes().to_vec()), true); + state.agent_owner_cache.insert( + (tenant.community(), agent.to_bytes().to_vec()), + owner.to_bytes().to_vec(), + ); state.observer_owner_cache.insert(owner_key, true); } link diff --git a/crates/buzz-relay/src/audio/handler.rs b/crates/buzz-relay/src/audio/handler.rs index b3b09cdb41..07aca2bbd2 100644 --- a/crates/buzz-relay/src/audio/handler.rs +++ b/crates/buzz-relay/src/audio/handler.rs @@ -3004,6 +3004,9 @@ impl HuddleAdmissionGuard { /// Why [`check_membership_for_admission`] refused: the caller lacks the /// authority, or a dependency that decides it could not be read. +const AGENT_DM_HUDDLE_REFUSED: &str = + "agents cannot join huddles in direct messages except with their owner"; + #[derive(Debug)] enum AdmissionRefusal { Denied(&'static str), @@ -3204,6 +3207,20 @@ async fn check_membership_for_admission( "only members can join huddles in this channel", )); } + for (scope_id, scope) in [(lifecycle_parent_id, write_scope), (channel_id, &channel)] { + if !crate::handlers::ingest::agent_dm_write_allowed( + tenant.community(), + state, + scope_id, + pubkey_bytes, + scope, + ) + .await + .map_err(AdmissionRefusal::Dependency)? + { + return Err(AdmissionRefusal::Denied(AGENT_DM_HUDDLE_REFUSED)); + } + } // Fast path: already a member. let is_member = state @@ -8050,6 +8067,67 @@ mod tests { mod postgres_tests { use super::*; + #[tokio::test] + #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] + async fn agent_joins_dm_huddles_only_with_its_owner() { + let state = audio_test_state_real_db() + .await + .expect("postgres-ci provides a database"); + let pool = state.db.pool().clone(); + let (tenant, _parent_id, _member_key) = seed_audio_fixture(&pool).await; + let community = tenant.community(); + let (owner, agent, stranger) = ( + nostr::Keys::generate().public_key().to_bytes(), + nostr::Keys::generate().public_key().to_bytes(), + nostr::Keys::generate().public_key().to_bytes(), + ); + for key in [&owner, &agent, &stranger] { + state + .db + .ensure_user(community, key) + .await + .expect("ensure user"); + } + state + .db + .set_agent_owner_for_authorization(community, &agent, &owner) + .await + .expect("link agent owner"); + let open_dm = |members: [&[u8; 32]; 2]| { + let state = state.clone(); + let members: Vec<[u8; 32]> = members.iter().map(|k| **k).collect(); + async move { + let refs: Vec<&[u8]> = members.iter().map(|k| k.as_slice()).collect(); + state + .db + .open_dm(community, &refs, refs[0]) + .await + .expect("open dm") + .0 + .id + } + }; + let stranger_dm = open_dm([&agent, &stranger]).await; + let owner_dm = open_dm([&agent, &owner]).await; + + assert!(matches!( + check_membership_for_admission(&state, &tenant, stranger_dm, &agent, None).await, + Err(AdmissionRefusal::Denied(AGENT_DM_HUDDLE_REFUSED)) + )); + assert!( + check_membership_for_admission(&state, &tenant, stranger_dm, &stranger, None) + .await + .is_ok(), + "a human still joins the DM huddle" + ); + assert!( + check_membership_for_admission(&state, &tenant, owner_dm, &agent, None) + .await + .is_ok(), + "an agent joins its owner-only DM huddle" + ); + } + /// Joining a huddle is a write. For an ephemeral huddle the joiner /// needs a writing role in the huddle itself and in its lifecycle /// parent, at the pre-join check and again at commit. diff --git a/crates/buzz-relay/src/handlers/command_executor.rs b/crates/buzz-relay/src/handlers/command_executor.rs index 1772ec3da8..14559007e3 100644 --- a/crates/buzz-relay/src/handlers/command_executor.rs +++ b/crates/buzz-relay/src/handlers/command_executor.rs @@ -27,7 +27,10 @@ use buzz_workflow::executor::TriggerContext; use crate::state::AppState; use crate::webhook_secret; -use super::ingest::{extract_channel_id, IngestAuth, IngestError, IngestResult}; +use super::ingest::{ + agent_dm_allowed, agent_owner_cached, extract_channel_id, IngestAuth, IngestError, + IngestResult, AGENT_DM_REFUSED, +}; use super::side_effects::{ emit_group_discovery_events, emit_membership_notification, emit_system_message, publish_dm_visibility_snapshot, @@ -291,6 +294,25 @@ fn compute_definition_hash(json_str: &str) -> Vec { Sha256::digest(json_str.as_bytes()).to_vec() } +/// An agent may only open or widen a DM into one whose participants are +/// exactly itself and its owner. Humans pass untouched. +async fn check_agent_dm_participants( + tenant: &TenantContext, + state: &AppState, + self_bytes: &[u8], + participants: &[Vec], +) -> Result<(), IngestError> { + let owner = agent_owner_cached(state, tenant.community(), self_bytes) + .await + .map_err(|e| IngestError::Internal(format!("error: agent owner lookup: {e}")))?; + match owner { + Some(owner) if !agent_dm_allowed(self_bytes, &owner, participants) => { + Err(IngestError::Rejected(AGENT_DM_REFUSED.into())) + } + _ => Ok(()), + } +} + async fn handle_dm_open( tenant: &TenantContext, state: &Arc, @@ -329,6 +351,8 @@ async fn handle_dm_open( } } + check_agent_dm_participants(tenant, state, &self_bytes, &all_bytes).await?; + // Persist the command event (idempotency) — returns open transaction let tx = match persist_command_event(&state.db, tenant, event, None).await? { PersistResult::Duplicate => { @@ -490,6 +514,7 @@ async fn handle_dm_add_member( "invalid: DM supports at most 9 participants".into(), )); } + check_agent_dm_participants(tenant, state, &self_bytes, &all_bytes).await?; // Persist the command event — returns open transaction let tx = match persist_command_event(&state.db, tenant, event, None).await? { diff --git a/crates/buzz-relay/src/handlers/ingest.rs b/crates/buzz-relay/src/handlers/ingest.rs index 46a1c81f28..c8361bfab3 100644 --- a/crates/buzz-relay/src/handlers/ingest.rs +++ b/crates/buzz-relay/src/handlers/ingest.rs @@ -940,6 +940,114 @@ impl ChannelWrite { const NOT_A_CHANNEL_MEMBER: &str = "restricted: not a channel member"; const MEMBERS_ONLY_POSTING: &str = "restricted: only members can post in this channel"; +pub(crate) const AGENT_DM_REFUSED: &str = + "restricted: agents cannot post in direct messages; start a Solo chat that includes your owner instead"; + +/// The stored owner of `pubkey` when it is an agent (`users.agent_owner_pubkey`), +/// or `None` for a human or unknown key. Only a confirmed owner is cached: the +/// link is first-write-wins and never changes once set, but a missing link can +/// be written later, possibly by another relay process. +pub(crate) async fn agent_owner_cached( + state: &AppState, + community_id: CommunityId, + pubkey_bytes: &[u8], +) -> Result>, buzz_db::DbError> { + let key = (community_id, pubkey_bytes.to_vec()); + if let Some(owner) = state.agent_owner_cache.get(&key) { + return Ok(Some(owner)); + } + let owner = state + .db + .get_agent_channel_policy(community_id, pubkey_bytes) + .await? + .and_then(|(_, owner)| owner); + if let Some(owner) = &owner { + state.agent_owner_cache.insert(key, owner.clone()); + } + Ok(owner) +} + +/// Whether `participants` may be a DM that includes the agent `agent`: only +/// when it is exactly the agent and `owner`. +pub(crate) fn agent_dm_allowed(agent: &[u8], owner: &[u8], participants: &[Vec]) -> bool { + participants.len() == 2 + && participants.iter().any(|p| p == agent) + && participants.iter().any(|p| p == owner) +} + +/// The DM rule for kinds that bypass the generic `Post` gate: an agent may +/// change metadata (kind:9002, which also posts a system message) only in its +/// owner-only DM, and may never add DM members (kind:9000), since an addition +/// to an owner-only DM always widens it. +async fn check_agent_dm_admin_write( + community_id: CommunityId, + state: &AppState, + ch_id: Uuid, + pubkey_bytes: &[u8], + channel: &buzz_db::channel::ChannelRecord, + kind: u32, +) -> Result<(), String> { + if channel.channel_type != buzz_core::channel::ChannelType::Dm.as_str() { + return Ok(()); + } + match kind { + KIND_NIP29_EDIT_METADATA => { + check_agent_dm_write(community_id, state, ch_id, pubkey_bytes, channel).await + } + KIND_NIP29_PUT_USER => match agent_owner_cached(state, community_id, pubkey_bytes) + .await + .map_err(|e| format!("error: database error: {e}"))? + { + Some(_) => Err(AGENT_DM_REFUSED.to_string()), + None => Ok(()), + }, + _ => Ok(()), + } +} + +/// Whether `pubkey` may write in `channel` under the agent DM rule: agents +/// never write in a DM, except one whose members are exactly the agent and +/// its owner. Humans and non-DM channels are always allowed. +pub(crate) async fn agent_dm_write_allowed( + community_id: CommunityId, + state: &AppState, + ch_id: Uuid, + pubkey_bytes: &[u8], + channel: &buzz_db::channel::ChannelRecord, +) -> Result { + if channel.channel_type != buzz_core::channel::ChannelType::Dm.as_str() { + return Ok(true); + } + let Some(owner) = agent_owner_cached(state, community_id, pubkey_bytes).await? else { + return Ok(true); + }; + let members: Vec> = state + .db + .get_members_for_event_write(community_id, ch_id) + .await? + .into_iter() + .map(|m| m.pubkey) + .collect(); + Ok(agent_dm_allowed(pubkey_bytes, &owner, &members)) +} + +/// [`agent_dm_write_allowed`] as a channel-gate verdict. +pub(crate) async fn check_agent_dm_write( + community_id: CommunityId, + state: &AppState, + ch_id: Uuid, + pubkey_bytes: &[u8], + channel: &buzz_db::channel::ChannelRecord, +) -> Result<(), String> { + if agent_dm_write_allowed(community_id, state, ch_id, pubkey_bytes, channel) + .await + .map_err(|e| format!("error: database error: {e}"))? + { + Ok(()) + } else { + Err(AGENT_DM_REFUSED.to_string()) + } +} /// The channel write gate: member OR open-visibility channel, plus, for /// [`ChannelWrite::Post`], the role-table write rule ([`may_post`]). @@ -990,6 +1098,9 @@ pub(crate) async fn check_channel_membership( { return Err(MEMBERS_ONLY_POSTING.to_string()); } + if write == ChannelWrite::Post { + check_agent_dm_write(community_id, state, ch_id, pubkey_bytes, channel).await?; + } Ok(()) } @@ -2914,6 +3025,24 @@ async fn ingest_event_inner( // row is missing (global event, kind:9007 pre-create) this is `None` and // fan-out performs its own fresh fail-closed lookup — `None` is never // "assume open" (fence 1). + if let (Some(ch_id), Some(row)) = (channel_id, &channel_row) { + check_agent_dm_admin_write( + tenant.community(), + state, + ch_id, + &pubkey_bytes, + row, + kind_u32, + ) + .await + .map_err(|e| { + if e == AGENT_DM_REFUSED { + IngestError::Rejected(e) + } else { + IngestError::Internal(e) + } + })?; + } let threaded_visibility = match (channel_id, &channel_row) { (Some(ch_id), Some(row)) => state .channel_visibility_cached(tenant.community(), ch_id, Some(row)) @@ -6982,6 +7111,262 @@ mod postgres_tests { .map(|_| ()) } + struct AgentDmFixture { + state: Arc, + tenant: TenantContext, + owner: nostr::Keys, + agent: nostr::Keys, + stranger: nostr::Keys, + } + + async fn agent_dm_fixture() -> AgentDmFixture { + let db_url = std::env::var("BUZZ_TEST_DATABASE_URL") + .or_else(|_| std::env::var("DATABASE_URL")) + .unwrap_or_else(|_| "postgres://buzz:buzz_dev@localhost:5432/buzz".to_string()); // sadscan:disable np.postgres.1 + let pool = sqlx::PgPool::connect(&db_url) + .await + .expect("connect test Postgres"); + let state = build_canvas_ingest_state(&db_url, &pool).await; + let host = format!("agent-dm-{}.test", Uuid::new_v4().simple()); + let community = state + .db + .ensure_configured_community(&host) + .await + .expect("community") + .id; + let tenant = TenantContext::resolved(community, &host); + let (owner, agent, stranger) = ( + nostr::Keys::generate(), + nostr::Keys::generate(), + nostr::Keys::generate(), + ); + for keys in [&owner, &agent, &stranger] { + state + .db + .ensure_user(community, keys.public_key().as_bytes()) + .await + .expect("ensure user"); + } + assert!(state + .db + .set_agent_owner_for_authorization( + community, + agent.public_key().as_bytes(), + owner.public_key().as_bytes(), + ) + .await + .expect("link agent owner")); + AgentDmFixture { + state, + tenant, + owner, + agent, + stranger, + } + } + + impl AgentDmFixture { + async fn open_dm(&self, members: &[&nostr::Keys]) -> Uuid { + let owned: Vec<[u8; 32]> = members.iter().map(|k| k.public_key().to_bytes()).collect(); + let pubkeys: Vec<&[u8]> = owned.iter().map(|b| b.as_slice()).collect(); + self.state + .db + .open_dm(self.tenant.community(), &pubkeys, pubkeys[0]) + .await + .expect("open dm") + .0 + .id + } + + async fn ingest( + &self, + author: &nostr::Keys, + kind: u16, + tags: Vec, + ) -> Result<(), IngestError> { + let event = EventBuilder::new(Kind::Custom(kind), "hi") + .tags(tags) + .sign_with_keys(author) + .expect("sign"); + let auth = IngestAuth::Http { + pubkey: author.public_key(), + scopes: Scope::all_known(), + auth_method: HttpAuthMethod::Nip98, + }; + let tracer: Arc = Arc::new(VecTracer::default()); + ingest_event_inner(&self.state, &tracer, &self.tenant, event, auth) + .await + .map(|_| ()) + } + + async fn post(&self, author: &nostr::Keys, channel_id: Uuid) -> Result<(), IngestError> { + self.ingest( + author, + 9, + vec![nostr::Tag::parse(["h", &channel_id.to_string()]).unwrap()], + ) + .await + } + } + + fn assert_agent_dm_refused(result: Result<(), IngestError>) { + match result { + Err(IngestError::Rejected(reason)) => assert_eq!(reason, AGENT_DM_REFUSED), + other => panic!("agent DM write must be refused, got {other:?}"), + } + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn agent_owner_lookup_does_not_cache_a_missing_link() { + let f = agent_dm_fixture().await; + let community = f.tenant.community(); + let late = nostr::Keys::generate(); + let late_bytes = late.public_key().to_bytes(); + f.state + .db + .ensure_user(community, &late_bytes) + .await + .expect("ensure user"); + + assert_eq!( + agent_owner_cached(&f.state, community, &late_bytes) + .await + .expect("lookup"), + None + ); + f.state + .db + .set_agent_owner_for_authorization( + community, + &late_bytes, + f.owner.public_key().as_bytes(), + ) + .await + .expect("link agent owner"); + assert_eq!( + agent_owner_cached(&f.state, community, &late_bytes) + .await + .expect("lookup"), + Some(f.owner.public_key().to_bytes().to_vec()), + "an owner linked after a miss must be seen at once" + ); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn agent_cannot_post_in_a_dm_with_someone_other_than_its_owner() { + let f = agent_dm_fixture().await; + let with_stranger = f.open_dm(&[&f.agent, &f.stranger]).await; + let group = f.open_dm(&[&f.agent, &f.owner, &f.stranger]).await; + + assert_agent_dm_refused(f.post(&f.agent, with_stranger).await); + assert_agent_dm_refused(f.post(&f.agent, group).await); + f.post(&f.stranger, with_stranger) + .await + .expect("a human still posts in the same DM"); + f.post(&f.owner, group) + .await + .expect("the owner still posts in the group DM"); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn agent_can_post_in_a_dm_with_only_its_owner() { + let f = agent_dm_fixture().await; + let owner_dm = f.open_dm(&[&f.owner, &f.agent]).await; + + f.post(&f.agent, owner_dm) + .await + .expect("an owner-only DM stays open to the agent"); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn agent_dm_open_is_limited_to_its_owner() { + let f = agent_dm_fixture().await; + let p = |keys: &nostr::Keys| nostr::Tag::parse(["p", &keys.public_key().to_hex()]).unwrap(); + + assert_agent_dm_refused( + f.ingest(&f.agent, KIND_DM_OPEN as u16, vec![p(&f.stranger)]) + .await, + ); + assert_agent_dm_refused( + f.ingest( + &f.agent, + KIND_DM_OPEN as u16, + vec![p(&f.owner), p(&f.stranger)], + ) + .await, + ); + f.ingest(&f.agent, KIND_DM_OPEN as u16, vec![p(&f.owner)]) + .await + .expect("an agent may open a DM with only its owner"); + f.ingest(&f.stranger, KIND_DM_OPEN as u16, vec![p(&f.agent)]) + .await + .expect("a human may still open a DM that includes an agent"); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn agent_cannot_put_users_into_its_owner_dm() { + let f = agent_dm_fixture().await; + let owner_dm = f.open_dm(&[&f.owner, &f.agent]).await; + + assert_agent_dm_refused( + f.ingest( + &f.agent, + KIND_NIP29_PUT_USER as u16, + vec![ + nostr::Tag::parse(["h", &owner_dm.to_string()]).unwrap(), + nostr::Tag::parse(["p", &f.stranger.public_key().to_hex(), "member"]).unwrap(), + ], + ) + .await, + ); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn agent_cannot_set_metadata_in_a_dm_with_someone_other_than_its_owner() { + let f = agent_dm_fixture().await; + let with_stranger = f.open_dm(&[&f.agent, &f.stranger]).await; + let topic = |channel: Uuid| { + vec![ + nostr::Tag::parse(["h", &channel.to_string()]).unwrap(), + nostr::Tag::parse(["topic", "hello"]).unwrap(), + ] + }; + + assert_agent_dm_refused( + f.ingest( + &f.agent, + KIND_NIP29_EDIT_METADATA as u16, + topic(with_stranger), + ) + .await, + ); + } + + #[tokio::test] + #[ignore = "requires Postgres"] + async fn agent_cannot_add_members_to_its_owner_dm() { + let f = agent_dm_fixture().await; + let owner_dm = f.open_dm(&[&f.owner, &f.agent]).await; + + assert_agent_dm_refused( + f.ingest( + &f.agent, + KIND_DM_ADD_MEMBER as u16, + vec![ + nostr::Tag::parse(["h", &owner_dm.to_string()]).unwrap(), + nostr::Tag::parse(["p", &f.stranger.public_key().to_hex()]).unwrap(), + ], + ) + .await, + ); + } + async fn create_role(admin: &sqlx::PgPool, role: &str) -> Result<(), sqlx::Error> { role_sql(admin, format!("CREATE ROLE {role} NOLOGIN")).await } diff --git a/crates/buzz-relay/src/state.rs b/crates/buzz-relay/src/state.rs index 9731c20d92..59e0b52b63 100644 --- a/crates/buzz-relay/src/state.rs +++ b/crates/buzz-relay/src/state.rs @@ -1588,6 +1588,11 @@ pub struct AppState { /// first-write-wins and set during auth before an agent's first event, /// so a short TTL only bounds staleness for the rare backfill race. pub author_type_cache: Arc), bool>>, + /// Confirmed agent owners for the DM write gate. Key: (community_id, + /// agent pubkey bytes). Value: `users.agent_owner_pubkey`. Absence is + /// never cached, because another process may link the owner later. + #[allow(clippy::type_complexity)] + pub agent_owner_cache: Arc), Vec>>, /// Community lifecycle answers for socket admission and the ephemeral /// write fence, served for /// [`crate::community_active::COMMUNITY_ACTIVE_MAX_AGE`] after their read's @@ -1905,6 +1910,12 @@ impl AppState { .time_to_live(std::time::Duration::from_secs(300)) .build(), ), + agent_owner_cache: Arc::new( + moka::sync::Cache::builder() + .max_capacity(10_000) + .time_to_live(std::time::Duration::from_secs(300)) + .build(), + ), community_active: Arc::new(crate::community_active::new_cache(shared_read_wait)), restriction_cache: Arc::new(crate::fenced_cache::FencedCache::new( 100_000, diff --git a/crates/buzz-relay/src/workflow_sink.rs b/crates/buzz-relay/src/workflow_sink.rs index 905d1c7b08..4994bfcd14 100644 --- a/crates/buzz-relay/src/workflow_sink.rs +++ b/crates/buzz-relay/src/workflow_sink.rs @@ -298,6 +298,21 @@ impl ActionSink for RelayActionSink { "workflow owner cannot post in destination channel".into(), )); } + crate::handlers::ingest::check_agent_dm_write( + tenant.community(), + &state, + channel_uuid, + &author_pubkey_bytes, + &channel, + ) + .await + .map_err(|e| { + if e == crate::handlers::ingest::AGENT_DM_REFUSED { + ActionSinkError::InvalidInput(e) + } else { + ActionSinkError::Database(e) + } + })?; // 3. Build kind:9 Nostr event // - Signed by relay keypair (event.pubkey = relay pubkey) @@ -1372,6 +1387,92 @@ mod postgres_tests { ); } + #[tokio::test] + #[ignore = "requires Postgres"] + async fn workflow_send_message_keeps_agents_out_of_dms() { + let state = test_state().await; + let (owner, agent, stranger) = ( + nostr::Keys::generate(), + nostr::Keys::generate(), + nostr::Keys::generate(), + ); + let host = format!("wf-agent-dm-{}.example", uuid::Uuid::new_v4().simple()); + let community = match state + .db + .create_community_with_owner( + &host, + &owner.public_key().to_hex(), + &nostr::Keys::generate(), + ) + .await + .map(|write| write.outcome) + .expect("create community") + { + CreateCommunityWithOwnerResult::Created(rec) => rec.id, + other => panic!("expected fresh community, got {other:?}"), + }; + for keys in [&owner, &agent, &stranger] { + state + .db + .ensure_user(community, &keys.public_key().to_bytes()) + .await + .expect("ensure user"); + } + state + .db + .set_agent_owner_for_authorization( + community, + &agent.public_key().to_bytes(), + &owner.public_key().to_bytes(), + ) + .await + .expect("link agent owner"); + let open_dm = |members: [&nostr::Keys; 2]| { + let state = state.clone(); + let keys: Vec<[u8; 32]> = members.iter().map(|k| k.public_key().to_bytes()).collect(); + async move { + let refs: Vec<&[u8]> = keys.iter().map(|k| k.as_slice()).collect(); + state + .db + .open_dm(community, &refs, refs[0]) + .await + .expect("open dm") + .0 + .id + } + }; + let stranger_dm = open_dm([&agent, &stranger]).await; + let owner_dm = open_dm([&agent, &owner]).await; + let sink = RelayActionSink::new(&state); + let agent_hex = agent.public_key().to_hex(); + + let err = sink + .send_message( + community, + &stranger_dm.to_string(), + "hi", + "hi", + &agent_hex, + None, + ) + .await + .expect_err("an agent's workflow must not post in a DM with a stranger"); + assert!( + matches!(&err, ActionSinkError::InvalidInput(m) if m == crate::handlers::ingest::AGENT_DM_REFUSED), + "{err:?}" + ); + sink.send_message( + community, + &owner_dm.to_string(), + "hi", + "hi", + &agent_hex, + None, + ) + .await + .expect("an agent's workflow may post in its owner-only DM"); + } + #[tokio::test] #[ignore = "requires Postgres"] async fn workflow_reply_to_missing_parent_errors() {