From 97d5a46cc6e024e1c07134b59758c826e0272ba2 Mon Sep 17 00:00:00 2001 From: morgmart <98432065+morgmart@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:01:55 -0800 Subject: [PATCH] feat(relay): grow DMs in place, identified by their people (#9125) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Lets a DM grow. Today adding someone to a DM always starts a new DM. This makes the relay side of "growable DMs" work. Joining an existing DM, and seeing its history, is always opt-in: without `["history", "include"]` the relay never puts anyone into an existing DM, so older clients can't add anyone to one unseen. - **Opt-in tag on kind:41010 and kind:41011.** `["history", "include"]`, or `["history", "ask"]` on 41011, is the only way anyone joins an existing DM. Any other value is refused. - **41011 with the tag:** people and agents join this DM with its history. When people join, the DM's identity moves to the grown set of people, so messaging only the original people afterwards starts a new DM. - **A DM of at most one person never gains people in place**, even with the tag. Adding a person to you-and-your-agents starts or opens a DM of the people, and the original keeps its members. Agents still join it in place. - **41011 without the tag:** finds or makes a DM of the source's people plus whoever is added, as an untagged 41010 does, and adds no one to an existing DM. Agents already in the source stay behind; agents named in the add join the new DM. - **41011 with `["history", "ask"]`:** part of the protocol, because desktop and mobile use it to know when to ask about history. Agents alone, and people added to a DM of at most one person, are handled as with `include`. People who would join a DM of two or more people are refused with exactly `needs-choice: history` and nothing changes; the client asks, then sends the add again tagged `include` or untagged. Agents can't send it, and it isn't accepted on 41010. - **41010 with the tag:** finds the DM of the named people and adds any named agents it lacks. A DM still identified by all its members (made without the tag) moves to its people's identity when reopened this way. - **41010 without the tag:** finds the DM of those people, which agents may have joined, or creates a DM of exactly the named members. There is one DM per group of people, and agents joining it don't fork it (Morgan's product decision), so no second DM of the same people is ever created. A DM made this way with agents named gets an all-members fingerprint, so it never collides with the people's DM. - **A DM of people is identified by its people.** Agents don't change which DM it is and don't count toward the 9-person limit. There is no agent limit, matching channels. A DM with at most one person (you and your agents) is identified by all its members: an agent joining it moves its identity, so reopening the original pair starts a new DM. - **Collisions.** If people join and a DM of the grown set already exists, the relay returns it (`response:{"channel_id","created":false}`) and changes nothing here. Agents named with them join that DM. Agents alone join in place; if the identity the DM would move to is already taken (only possible for a DM of at most one person, or one still identified by all its members), the DM gives up its identity, so reopening its old members starts a new DM. - **One locked step.** Every DM membership write rereads the DM's members under its membership lock, checks the agents actually joining, and compares the DM's identity with the fingerprint actually stored. Starting a new DM from a DM uses the members it has at that moment. `created` is true only when this request made the DM, even if a concurrent open won the race. - **Agent add policies.** Putting someone else's agent in a DM with anyone besides you follows its `channel_add_policy`, the same rule as channels. That covers every agent in a new DM started from another one, and only the agents that join when a DM grows or is reopened. Messaging an agent alone ignores it, as today. - **Only people grow DMs.** An agent can't send the history tag on 41010 or 41011, so a DM an agent opens is identified by all its members and an agent can't take over or join a DM of its owner's people. Growing never reveals a DM the actor isn't in. The relay can't be added to any DM. - **The 9-person limit counts the caller only if they're a person**, so an agent can open a DM with nine people. - **A new DM carries people, not agents.** Every fork (Start new DM, the tagless 41011, a person added to an agent-only DM) holds the source's people plus the explicit additions. Agents can be added back later, so no agent's add policy can block Start new DM. - **Removing an agent keeps an old DM its people's.** A DM identified by all its members moves to its people's identity when an agent leaves or is removed, unless they already have a DM. - **Leaving and removing agents.** kind:9022 lets anyone leave a DM, and kind:9001 lets you remove yourself or your own agent (as deleting an agent does). kind:9000 and every other 9001 are refused on DMs; members join only through 41010/41011. - **Removals keep identity in step.** When anyone leaves or is removed, including moderation kicks (which remove members directly in the database), the DM keeps its identity only if its remaining members still match it. Otherwise it gives the identity up under the same membership lock: it keeps its history, and opening that group again starts a new DM. Removing an agent from a group DM keeps it that group's DM. - **The relay's moderation DM stays two-party**, on both 41010 and 41011. - SDK `build_dm_add_member(..., include_history)`, the opt-in `build_dm_open_with_history` (`build_dm_open` keeps the exact-members behavior; neither caps pubkeys, since the relay enforces nine people and agents do not count), and CLI `buzz dms add-member --include-history`. Without the flag the CLI keeps the old behavior. Removing other people (beyond moderation kicks) and DM naming are out of scope. Client follow-ups: block/buzz-app#2670 (desktop, sends the tag for history adds, agent adds, and New message opens that show an existing DM) and the mobile PR (sends it after its choice dialog). **Deploy this relay change before the app PR merges:** an older relay ignores the history tag, so the app's Include history would start a new DM instead. ### Decisions and known gaps - **No agent cap, on purpose.** This matches channels. The guard is the add policy instead: every agent the caller doesn't own needs its `channel_add_policy` to allow it when it joins a DM that holds anyone besides the caller and that one agent. So a DM stuffed with 40 agents whose policy is `nobody` is refused. Covered by `adding_an_agent_follows_its_add_policy` and `opening_with_several_agents_follows_their_add_policy`. - **A tagless add opens the DM of the people plus the additions.** Older clients forking a DM now leave its existing agents behind, as the new apps do. That shares less than before, never more. - **Where the protocol is documented.** kind:41010 and kind:41011 have no NIP today. The history tag is documented on the SDK builders (the add-member builder also documents `ask` and its `needs-choice: history` refusal, which it doesn't send) and in the CLI `--include-history` help, and the `created` field of the response is documented on the SDK builder. - **Known gap: lost announcements on retry.** The membership change and the idempotency record commit separately, the same pattern main uses for every DM command. If the membership change commits but the idempotency commit then fails, a client retry finds the members already there and returns success without posting the join messages, notifications or the new-DM announcement. Membership and history are correct. This needs a commit failure between the two writes, and fixing it means moving the DM writes into the idempotency transaction for all DM commands, so it's out of scope here. ### Rollout and rollback - **No kill switch needed.** The new behavior is opt-in per event: clients that don't send `["history", "include"]` get the old behavior. - **If the relay rolls back,** DMs that grew are no longer found by their people, so opening one starts a new DM. History stays in the grown DM and no data is corrupted. ### Related issue None found. ### Testing - Postgres-backed handler tests (`handlers::dm_growth_postgres_tests`, 44 cases) go through `ingest_event`: growing with and without history, the tagless 41010 and 41011 paths adding no one to an existing DM, collisions, agents joining in place only with the tag, per-agent owner DMs, the people-only limit, add policies (including several agents with no other person), agent actors, not revealing a DM the actor isn't in, the moderation DM on both kinds, a person added to an agent-only DM with the tag starting a separate DM, unknown history values, 9000 refused, leaving, owners removing their agents, kicks releasing or keeping identity, legacy fingerprints reconciled on agent join and tagged reopen (with the collision case), an agent joining a one-person DM whose grown identity is taken, untagged adds that name a person and an agent starting a DM of exactly those members, `ask` adding agents and refusing people, untagged opens of a group's people finding their DM with its agents (after an agent joined in place, and after one of two agents left), reopening past an existing `owner_only` agent, concurrent opens all adding their agents, new DMs carrying only people (and named agents), live membership, the relay key refused, and an agent opening a nine-person DM. Each new guard was mutation-checked: removing it turns a test red. - At 990f8b2ed: the 36 handler tests, SDK and CLI tests, clippy (`-D warnings`) and fmt pass, and the push passed the full pre-push hook. Every guard added in review was mutation-checked. The lost-insert race and the stale-member fork are forced with explicit lock waits, not timing. - Not yet done: exercising it against a running local relay, and a human test. Human test steps (local relay + app on the paired app branch): open a DM with one person, open its access dialog, add a second person and choose **Include history**: they join the same DM and see earlier messages; then message only the original person: a new DM opens. Add a person with **Start new DM**: a new DM of the people opens, without any agents, and the original is unchanged. Add an agent: it joins the same DM directly. In a DM with only you and an agent, add a person: a new DM of you and that person opens without a question, and the agent DM is unchanged. Leave a group DM: you're removed, and messaging the group again starts a new DM. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com> Co-authored-by: Carl Co-authored-by: Claude Opus 5.5 --- crates/buzz-cli/src/commands/dms.rs | 16 +- crates/buzz-cli/src/lib.rs | 8 +- .../src/store/admission_postgres_tests.rs | 26 +- crates/buzz-db/src/store/channel_members.rs | 6 +- crates/buzz-db/src/store/dm.rs | 911 ++++++++- crates/buzz-db/src/store/dm_postgres_tests.rs | 21 +- .../buzz-db/src/store/relay_admin_actions.rs | 4 + .../src/handlers/command_executor.rs | 530 +++-- .../src/handlers/dm_growth_postgres_tests.rs | 1775 +++++++++++++++++ .../handlers/group_state_postgres_tests.rs | 2 + crates/buzz-relay/src/handlers/mod.rs | 2 + .../src/handlers/moderation_notices.rs | 3 + .../buzz-relay/src/handlers/side_effects.rs | 22 + crates/buzz-sdk/src/builders.rs | 101 +- 14 files changed, 3182 insertions(+), 245 deletions(-) create mode 100644 crates/buzz-relay/src/handlers/dm_growth_postgres_tests.rs diff --git a/crates/buzz-cli/src/commands/dms.rs b/crates/buzz-cli/src/commands/dms.rs index 092e4a3cb3..dfe4974dd7 100644 --- a/crates/buzz-cli/src/commands/dms.rs +++ b/crates/buzz-cli/src/commands/dms.rs @@ -73,8 +73,10 @@ async fn list_dms(client: &BuzzClient, limit: u32) -> Result Result<(), CliError> { - if pubkeys.is_empty() || pubkeys.len() > 8 { - return Err(CliError::Usage("--pubkey: must provide 1-8 pubkeys".into())); + if pubkeys.is_empty() { + return Err(CliError::Usage( + "--pubkey: must provide at least 1 pubkey".into(), + )); } for pk in pubkeys { validate_hex64(pk)?; @@ -137,11 +139,13 @@ pub async fn cmd_add_dm_member( client: &BuzzClient, channel_id: &str, pubkey: &str, + include_history: bool, ) -> Result<(), CliError> { let channel_uuid = parse_uuid(channel_id)?; validate_hex64(pubkey)?; - let builder = buzz_sdk::build_dm_add_member(channel_uuid, pubkey).map_err(sdk_err)?; + let builder = + buzz_sdk::build_dm_add_member(channel_uuid, pubkey, include_history).map_err(sdk_err)?; let event = client.sign_event(builder).await?; let resp = client.submit_event(event).await?; @@ -154,7 +158,11 @@ pub async fn dispatch(cmd: crate::DmsCmd, client: &BuzzClient) -> Result<(), Cli match cmd { DmsCmd::List { limit } => cmd_list_dms(client, limit).await, DmsCmd::Open { pubkeys } => cmd_open_dm(client, &pubkeys).await, - DmsCmd::AddMember { channel, pubkey } => cmd_add_dm_member(client, &channel, &pubkey).await, + DmsCmd::AddMember { + channel, + pubkey, + include_history, + } => cmd_add_dm_member(client, &channel, &pubkey, include_history).await, DmsCmd::Hide { channel } => cmd_hide_dm(client, &channel).await, } } diff --git a/crates/buzz-cli/src/lib.rs b/crates/buzz-cli/src/lib.rs index f01cd89df1..e523890d25 100644 --- a/crates/buzz-cli/src/lib.rs +++ b/crates/buzz-cli/src/lib.rs @@ -1343,7 +1343,8 @@ pub enum DmsCmd { }, /// Open a new direct message with one or more users Open { - /// User pubkey(s) to DM (64-char hex, 1-8) + /// User pubkey(s) to DM (64-char hex). A DM holds at most 9 people, + /// you included; agents do not count. #[arg(long = "pubkey")] pubkeys: Vec, }, @@ -1355,6 +1356,11 @@ pub enum DmsCmd { /// User pubkey to add (64-char hex) #[arg(long)] pubkey: String, + /// Add them to this DM with its history, instead of starting a new DM + /// of its people and them (agents stay behind). A person added to a DM of one person and their agents + /// always starts a new DM. Agents cannot use this. + #[arg(long)] + include_history: bool, }, /// Hide a DM conversation from your DM list Hide { diff --git a/crates/buzz-db/src/store/admission_postgres_tests.rs b/crates/buzz-db/src/store/admission_postgres_tests.rs index 8cef51834e..150f517922 100644 --- a/crates/buzz-db/src/store/admission_postgres_tests.rs +++ b/crates/buzz-db/src/store/admission_postgres_tests.rs @@ -498,9 +498,16 @@ async fn dm_writers_require_application_admission() { let participants: [&[u8]; 2] = [&[1; 32], &[2; 32]]; for community in &communities[1..] { assert_fenced( - super::dm::create_dm(&db.pool, *community, &participants, participants[0]) - .await - .expect_err("DM create must reject"), + super::dm::create_dm( + &db.pool, + *community, + &participants, + participants[0], + false, + &|_: &str, _: &[u8]| Ok(()), + ) + .await + .expect_err("DM create must reject"), ); assert_fenced( super::dm::hide_dm(&db.pool, *community, Uuid::new_v4(), participants[0]) @@ -508,9 +515,16 @@ async fn dm_writers_require_application_admission() { .expect_err("DM hide must reject"), ); } - super::dm::create_dm(&db.pool, communities[0], &participants, participants[0]) - .await - .expect("active DM create succeeds"); + super::dm::create_dm( + &db.pool, + communities[0], + &participants, + participants[0], + false, + &|_: &str, _: &[u8]| Ok(()), + ) + .await + .expect("active DM create succeeds"); } #[tokio::test] diff --git a/crates/buzz-db/src/store/channel_members.rs b/crates/buzz-db/src/store/channel_members.rs index 0d0286c784..b1377f6fbe 100644 --- a/crates/buzz-db/src/store/channel_members.rs +++ b/crates/buzz-db/src/store/channel_members.rs @@ -905,7 +905,10 @@ pub(crate) async fn put_members_with_event( /// tag, the TTL reaper's single UPDATE), and none of them takes the /// membership lock. So an archive either commits before [`put_members_on`] /// reads `archived_at`, or waits until this write commits. -async fn lock_channel_for_member_put(tx: &mut AdmittedTx, channel_id: Uuid) -> Result<()> { +pub(crate) async fn lock_channel_for_member_put( + tx: &mut AdmittedTx, + channel_id: Uuid, +) -> Result<()> { let community_id = tx.community(); acquire_channel_membership_lock(tx.conn(), community_id, channel_id).await?; lock_channel_ttl_shared_in_transaction(tx, channel_id).await?; @@ -1206,6 +1209,7 @@ pub async fn remove_member( if result.rows_affected() == 0 { return Err(DbError::MemberNotFound(channel_id)); } + crate::dm::release_dm_identity(tx.conn(), community_id, channel_id, pubkey).await?; tx.commit().await?; Ok(()) diff --git a/crates/buzz-db/src/store/dm.rs b/crates/buzz-db/src/store/dm.rs index 20b6b365ab..f32131bd8e 100644 --- a/crates/buzz-db/src/store/dm.rs +++ b/crates/buzz-db/src/store/dm.rs @@ -1,7 +1,13 @@ //! Direct message channel persistence. //! //! DMs are channels with channel_type='dm' and visibility='private'. -//! Participant sets are immutable -- adding a member creates a NEW DM. +//! +//! A DM is identified by its people: at most one DM exists for a set of +//! people, and "message these people" finds it. Agents are add-ons: they join +//! a DM without changing which DM it is (see [`dm_identity_hash`]). A DM can +//! grow in place ([`grow_dm`]); its identity then moves to the grown set. + +use std::collections::HashSet; use chrono::{DateTime, Utc}; use sha2::{Digest, Sha256}; @@ -59,6 +65,105 @@ pub fn compute_participant_hash(pubkeys: &[&[u8]]) -> [u8; 32] { hasher.finalize().into() } +/// The most people a DM can hold. Agents do not count. +pub const MAX_DM_PEOPLE: usize = 9; + +/// The fingerprint that identifies a DM with these `members`, of whom +/// `agents` are agents. +/// +/// A DM is identified by its people, so adding or removing an agent never +/// changes which DM it is. A DM with at most one person (someone and their +/// agents) is identified by all its members instead, so each such DM keeps its +/// own identity, as every DM did before agents were told apart. +pub fn dm_identity_hash(members: &[&[u8]], agents: &HashSet>) -> [u8; 32] { + let people: Vec<&[u8]> = members + .iter() + .copied() + .filter(|pk| !agents.contains(*pk)) + .collect(); + if people.len() >= 2 { + compute_participant_hash(&people) + } else { + compute_participant_hash(members) + } +} + +/// The fingerprint a DM of `members` gets when opened. With `by_people`, the +/// DM of its people ([`dm_identity_hash`]). Otherwise the DM of exactly these +/// members, as before agents were told apart: only callers who opt in decide +/// which DM their people share. +fn opened_identity_hash(members: &[&[u8]], agents: &HashSet>, by_people: bool) -> [u8; 32] { + if by_people { + dm_identity_hash(members, agents) + } else { + compute_participant_hash(members) + } +} + +/// How many of `members` are people rather than agents. +fn count_people(members: &[&[u8]], agents: &HashSet>) -> usize { + members.iter().filter(|pk| !agents.contains(**pk)).count() +} + +/// The pubkeys among `candidates` that belong to agents: users with an owner. +async fn agents_among<'e>( + executor: impl sqlx::PgExecutor<'e>, + community_id: CommunityId, + candidates: &[&[u8]], +) -> Result>> { + let candidates: Vec> = candidates.iter().map(|pk| pk.to_vec()).collect(); + let agents: Vec> = sqlx::query_scalar( + "SELECT pubkey FROM users \ + WHERE community_id = $1 AND pubkey = ANY($2) AND agent_owner_pubkey IS NOT NULL", + ) + .bind(community_id.as_uuid()) + .bind(&candidates) + .fetch_all(executor) + .await?; + Ok(agents.into_iter().collect()) +} + +/// Decides whether the caller may put an agent, given its +/// `channel_add_policy` and owner, into a DM with others. `Err` carries the +/// refusal. +pub type AgentAddPolicy<'a> = &'a (dyn Fn(&str, &[u8]) -> std::result::Result<(), String> + Sync); + +/// Refuse unless every agent in `joining`, other than `actor`, may join by +/// `policy`. +/// +/// Callers run this in the same transaction, and under the same locks, as the +/// write it guards, so it sees exactly who joins. +async fn check_joining_agents( + conn: &mut sqlx::PgConnection, + community_id: CommunityId, + actor: &[u8], + joining: &[&[u8]], + policy: AgentAddPolicy<'_>, +) -> Result<()> { + let joining: Vec> = joining + .iter() + .filter(|pk| **pk != actor) + .map(|pk| pk.to_vec()) + .collect(); + if joining.is_empty() { + return Ok(()); + } + let rows = sqlx::query( + "SELECT channel_add_policy::text AS policy, agent_owner_pubkey AS owner FROM users \ + WHERE community_id = $1 AND pubkey = ANY($2) AND agent_owner_pubkey IS NOT NULL", + ) + .bind(community_id.as_uuid()) + .bind(&joining) + .fetch_all(&mut *conn) + .await?; + for row in rows { + let agent_policy: String = row.try_get("policy")?; + let owner: Vec = row.try_get("owner")?; + policy(&agent_policy, &owner).map_err(DbError::AccessDenied)?; + } + Ok(()) +} + // -- DB functions ------------------------------------------------------------- /// Find an existing DM by its participant hash. @@ -68,6 +173,15 @@ pub async fn find_dm_by_participants( pool: &PgPool, community_id: CommunityId, participant_hash: &[u8], +) -> Result> { + find_dm_in(pool, community_id, participant_hash).await +} + +/// [`find_dm_by_participants`] on any executor, such as a transaction. +async fn find_dm_in<'e>( + executor: impl sqlx::PgExecutor<'e>, + community_id: CommunityId, + participant_hash: &[u8], ) -> Result> { let row = sqlx::query( r#" @@ -87,50 +201,137 @@ pub async fn find_dm_by_participants( ) .bind(community_id.as_uuid()) .bind(participant_hash) - .fetch_optional(pool) + .fetch_optional(executor) .await?; row.map(row_to_channel_record).transpose() } +/// The existing DM that opening a DM of `participants`, of whom `agents` are +/// agents, finds. With `by_people`, the DM of their people, or one made before +/// agents were told apart, identified by all its members. Without, the DM +/// identified by all of them, which for people alone is their DM, with any +/// agents that joined it: there is one DM per group of people. Failing that, +/// their people's DM when it holds exactly them now, as a DM that agents +/// joined in place does. +async fn find_opened_dm( + conn: &mut sqlx::PgConnection, + community_id: CommunityId, + participants: &[&[u8]], + agents: &HashSet>, + by_people: bool, +) -> Result> { + let people = dm_identity_hash(participants, agents); + let exact = compute_participant_hash(participants); + let (first, second) = if by_people { + (people, exact) + } else { + (exact, people) + }; + if let Some(found) = find_dm_in(&mut *conn, community_id, &first).await? { + return Ok(Some(found)); + } + if second == first { + return Ok(None); + } + let Some(found) = find_dm_in(&mut *conn, community_id, &second).await? else { + return Ok(None); + }; + if by_people { + return Ok(Some(found)); + } + let members: HashSet> = sqlx::query_scalar( + "SELECT pubkey FROM channel_members \ + WHERE community_id = $1 AND channel_id = $2 AND removed_at IS NULL", + ) + .bind(community_id.as_uuid()) + .bind(found.id) + .fetch_all(&mut *conn) + .await? + .into_iter() + .collect(); + let wanted: HashSet> = participants.iter().map(|pk| pk.to_vec()).collect(); + Ok((members == wanted).then_some(found)) +} + /// Create a new DM channel for the given participant pubkeys, or return the /// existing one if a DM with the same participant set already exists. /// /// Rules: -/// - `participants` must contain 2-9 entries (enforced here). +/// - `participants` must contain at least 2 entries, and at most +/// [`MAX_DM_PEOPLE`] people; agents do not count (enforced here). /// - `created_by` must be one of the participants. -/// - The operation is idempotent: same participant set -> same channel returned. +/// - The operation is idempotent: the same identity (see +/// [`opened_identity_hash`] for `by_people`) -> the same channel returned. +/// - A new DM's agents need `policy`'s permission ([`check_joining_agents`]), +/// except in a DM of just `created_by` and one agent: messaging an agent +/// alone is always allowed. +/// +/// Returns `(channel, was_created)`; `was_created` is false when the DM +/// already existed, including when a concurrent open made it first. pub async fn create_dm( pool: &PgPool, community_id: CommunityId, participants: &[&[u8]], created_by: &[u8], -) -> Result { - create_dm_if_missing(pool, community_id, participants, created_by) - .await - .map(|(channel, _)| channel) + by_people: bool, + policy: AgentAddPolicy<'_>, +) -> Result<(ChannelRecord, bool)> { + let mut tx = crate::begin_community_write_transaction( + pool, + community_id, + crate::observability::WriterOperation::EventWrite, + ) + .await?; + let found = find_or_create_dm( + tx.conn(), + community_id, + participants, + created_by, + by_people, + policy, + ) + .await?; + tx.commit().await?; + Ok(found) } -/// Atomically create or reuse a DM without changing participant visibility. -/// -/// The boolean is true only when this call inserted the channel. Concurrent -/// callers for the same participant set reuse the winner's committed channel. +/// Create or reuse the DM of exactly `participants` without changing who has +/// it hidden, as a workflow sending a DM needs: only the interactive open +/// changes visibility. True only when this call made the DM. A new DM's agents +/// need no permission, as a workflow DMs its owner directly. pub async fn create_dm_if_missing( pool: &PgPool, community_id: CommunityId, participants: &[&[u8]], created_by: &[u8], +) -> Result<(ChannelRecord, bool)> { + create_dm( + pool, + community_id, + participants, + created_by, + false, + &|_: &str, _: &[u8]| Ok(()), + ) + .await +} + +/// [`create_dm`] on the caller's transaction, so a caller holding a DM's lock +/// makes the new DM without another connection. +async fn find_or_create_dm( + conn: &mut sqlx::PgConnection, + community_id: CommunityId, + participants: &[&[u8]], + created_by: &[u8], + by_people: bool, + policy: AgentAddPolicy<'_>, ) -> Result<(ChannelRecord, bool)> { if participants.len() < 2 { return Err(DbError::InvalidData( "DM requires at least 2 participants".to_string(), )); } - if participants.len() > 9 { - return Err(DbError::InvalidData( - "DM supports at most 9 participants".to_string(), - )); - } for pk in participants { if pk.len() != 32 { return Err(DbError::InvalidData(format!( @@ -139,15 +340,25 @@ pub async fn create_dm_if_missing( ))); } } + let agents = agents_among(&mut *conn, community_id, participants).await?; + if count_people(participants, &agents) > MAX_DM_PEOPLE { + return Err(DbError::InvalidData(format!( + "DM supports at most {MAX_DM_PEOPLE} people" + ))); + } - let hash = compute_participant_hash(participants); - - let mut tx = crate::begin_community_write_transaction( - pool, - community_id, - crate::observability::WriterOperation::EventWrite, - ) - .await?; + if let Some(existing) = + find_opened_dm(&mut *conn, community_id, participants, &agents, by_people).await? + { + return Ok((existing, false)); + } + let hash = opened_identity_hash(participants, &agents, by_people); + // Messaging one agent alone needs no permission: a new direct DM shares + // no one's history. + let direct = participants.len() == 2 && participants.contains(&created_by); + if !direct { + check_joining_agents(conn, community_id, created_by, participants, policy).await?; + } // Name the DM based on participant count. let name = if participants.len() == 2 { @@ -158,15 +369,14 @@ pub async fn create_dm_if_missing( let id = Uuid::new_v4(); - let was_created = sqlx::query( + // A savepoint, so losing to a concurrent open of the same DM leaves the + // transaction usable. + let mut insert = sqlx::Connection::begin(&mut *conn).await?; + let inserted = sqlx::query( r#" INSERT INTO channels (id, community_id, name, channel_type, visibility, created_by, participant_hash) VALUES ($1, $2, $3, 'dm', 'private', $4, $5) - ON CONFLICT (community_id, participant_hash) - WHERE participant_hash IS NOT NULL - DO NOTHING - RETURNING id "#, ) .bind(id) @@ -174,31 +384,43 @@ pub async fn create_dm_if_missing( .bind(&name) .bind(created_by) .bind(hash.as_slice()) - .fetch_optional(tx.conn()) - .await? - .is_some(); - - if was_created { - // Add all participants as members with role='member'. - for pk in participants { - sqlx::query( - r#" - INSERT INTO channel_members (community_id, channel_id, pubkey, role, invited_by) - VALUES ($1, $2, $3, 'member', $4) - ON CONFLICT (community_id, channel_id, pubkey) DO UPDATE SET - sync_modified_at = CASE WHEN channel_members.removed_at IS NOT NULL THEN clock_timestamp() ELSE channel_members.sync_modified_at END, - removed_at = NULL, - removed_by = NULL, - role = EXCLUDED.role - "#, - ) - .bind(community_id.as_uuid()) - .bind(id) - .bind(*pk) - .bind(created_by) - .execute(tx.conn()) - .await?; + .execute(&mut *insert) + .await; + match inserted { + Err(sqlx::Error::Database(e)) if e.code().as_deref() == Some("23505") => { + insert.rollback().await?; + return match find_dm_in(&mut *conn, community_id, &hash).await? { + Some(existing) => Ok((existing, false)), + None => Err(DbError::InvalidData( + "a DM with these members already exists".to_string(), + )), + }; } + inserted => { + inserted?; + insert.commit().await?; + } + } + + // Add all participants as members with role='member'. + for pk in participants { + sqlx::query( + r#" + INSERT INTO channel_members (community_id, channel_id, pubkey, role, invited_by) + VALUES ($1, $2, $3, 'member', $4) + ON CONFLICT (community_id, channel_id, pubkey) DO UPDATE SET + sync_modified_at = CASE WHEN channel_members.removed_at IS NOT NULL THEN clock_timestamp() ELSE channel_members.sync_modified_at END, + removed_at = NULL, + removed_by = NULL, + role = EXCLUDED.role + "#, + ) + .bind(community_id.as_uuid()) + .bind(id) + .bind(*pk) + .bind(created_by) + .execute(&mut *conn) + .await?; } let row = sqlx::query( @@ -209,18 +431,15 @@ pub async fn create_dm_if_missing( nip29_group_id, topic_required, max_members, topic, topic_set_by, topic_set_at, purpose, purpose_set_by, purpose_set_at, labels, join_role, unlisted, auto_join - FROM channels - WHERE community_id = $1 AND participant_hash = $2 AND deleted_at IS NULL + FROM channels WHERE community_id = $1 AND id = $2 "#, ) .bind(community_id.as_uuid()) - .bind(hash.as_slice()) - .fetch_one(tx.conn()) + .bind(id) + .fetch_one(&mut *conn) .await?; - let record = row_to_channel_record(row)?; - tx.commit().await?; - Ok((record, was_created)) + Ok((row_to_channel_record(row)?, true)) } /// List all DM conversations for a given user, ordered by most recent activity. @@ -354,6 +573,16 @@ pub async fn list_dms_for_user( /// `created_by` is automatically added to `pubkeys` if not already present, /// ensuring the caller is always a participant in their own DM. /// +/// With `by_people`, the DM is found by its people ([`dm_identity_hash`]), so +/// it may hold agents that `pubkeys` does not name, and lack agents it does. +/// Adding those is [`grow_dm`]'s job. A DM made before agents were told apart +/// is still found by all its members. Without `by_people`, the DM found is +/// the one of exactly these members, agents included, or, when they are all +/// people, their DM, which agents may have joined: there is one DM per group +/// of people. A DM made is one of exactly these members. A found DM is +/// returned only to an active member of it, so naming a DM's people cannot be +/// used to see or join it. A new DM's agents need `policy`'s permission. +/// /// Returns `(channel, was_created)`: /// - `was_created = true` -- a new DM was created. /// - `was_created = false` -- an existing DM was returned. @@ -362,37 +591,472 @@ pub async fn open_dm( community_id: CommunityId, pubkeys: &[&[u8]], created_by: &[u8], + by_people: bool, + policy: AgentAddPolicy<'_>, ) -> Result<(ChannelRecord, bool)> { - // Merge created_by into the participant set (dedup handled by compute_participant_hash). - let mut all: Vec<&[u8]> = pubkeys.to_vec(); - if !all.contains(&created_by) { - all.push(created_by); + let mut all: Vec<&[u8]> = vec![created_by]; + for pk in pubkeys { + if !all.contains(pk) { + all.push(pk); + } } - // Enforce max before hitting the DB. - if all.len() > 9 { - return Err(DbError::InvalidData( - "DM supports at most 9 participants".to_string(), - )); + let agents = agents_among(pool, community_id, &all).await?; + if count_people(&all, &agents) > MAX_DM_PEOPLE { + return Err(DbError::InvalidData(format!( + "DM supports at most {MAX_DM_PEOPLE} people" + ))); } - let hash = compute_participant_hash(&all); - // Check for existing DM first (fast path, no transaction). - if let Some(existing) = find_dm_by_participants(pool, community_id, &hash).await? { - // Clear hidden_at for the caller so the DM reappears in their sidebar. - unhide_dm(pool, community_id, existing.id, created_by).await?; - return Ok((existing, false)); + let mut conn = pool.acquire().await?; + let existing = find_opened_dm(&mut conn, community_id, &all, &agents, by_people).await?; + drop(conn); + if let Some(existing) = existing { + return reopen_dm(pool, community_id, existing, created_by).await; } - // Create new DM. - let (channel, was_created) = create_dm_if_missing(pool, community_id, &all, created_by).await?; - if !was_created { - // A concurrent opener won after the fast-path lookup. This is still - // an interactive open, so retain the same visibility semantics. - unhide_dm(pool, community_id, channel.id, created_by).await?; + let (channel, created) = + create_dm(pool, community_id, &all, created_by, by_people, policy).await?; + if created { + Ok((channel, true)) + } else { + // A concurrent open made it first. + reopen_dm(pool, community_id, channel, created_by).await + } +} + +/// Return the existing DM `existing` to `caller`, who must be an active member +/// of it, and show it in their sidebar again. +async fn reopen_dm( + pool: &PgPool, + community_id: CommunityId, + existing: ChannelRecord, + caller: &[u8], +) -> Result<(ChannelRecord, bool)> { + if !crate::channel_members::is_member(pool, community_id, existing.id, caller).await? { + return Err(DbError::AccessDenied( + "a DM with these people already exists".to_string(), + )); + } + unhide_dm(pool, community_id, existing.id, caller).await?; + Ok((existing, false)) +} + +/// The outcome of [`grow_dm`]. +#[derive(Debug, Clone)] +pub enum DmGrowth { + /// The DM now holds everyone asked for. `added` lists those who were not + /// already active members, in the order asked. + Grown { + /// Pubkeys that became members. + added: Vec>, + }, + /// Another DM, with this ID, already has the grown set of people, so this + /// DM cannot take its identity. Nothing was written. + Existing(Uuid), + /// This DM has at most one person, and the additions would bring it to + /// two or more. Such a DM never gains people in place; the caller starts + /// a DM of everyone instead. Nothing was written. + PeopleStartNewDm, + /// People would join this DM of two or more people, and the caller asked + /// first: they choose whether those people see its history. Nothing was + /// written. + NeedsChoice, +} + +/// Add `additions` to the DM `channel_id` in place, keeping its history. +/// +/// Agents join a DM of two or more people without changing which DM it is. +/// Otherwise the DM's identity moves to the grown set ([`dm_identity_hash`]), so +/// opening a DM with the original members afterwards starts a new one. If +/// people join and a DM of the grown set already exists, nothing is written and +/// that DM is returned as [`DmGrowth::Existing`], provided `actor` is in it; +/// agents alone join in place, and the DM keeps the identity it has. People never +/// join a DM of at most one person: that is [`DmGrowth::PeopleStartNewDm`]. +/// +/// The DM's stored fingerprint is brought up to date even when nothing is +/// added, so a DM still identified by all its members (from before agents +/// were told apart) becomes its people's DM. A DM that gave its identity up +/// ([`release_dm_identity`]) takes a new one only when people join. Each agent +/// that joins needs `policy`'s permission ([`check_joining_agents`]). +/// +/// With `ask`, people joining a DM of two or more people are not added: that +/// is [`DmGrowth::NeedsChoice`], so the caller can ask whether they see its +/// history. Agents alone still join, and a DM of at most one person still +/// starts a new DM. +/// +/// `actor` must be an active member. The DM must be live and not archived, and +/// may hold at most [`MAX_DM_PEOPLE`] people afterwards. Re-adding members is +/// a no-op, so a retry after a lost commit acknowledgement is safe. +/// +/// Runs under the channel's membership locks ([`put_members`]'s), so it is +/// serialized against every other membership write and archive of the DM. +/// +/// [`put_members`]: crate::channel_members::put_members +pub async fn grow_dm( + pool: &PgPool, + community_id: CommunityId, + channel_id: Uuid, + actor: &[u8], + additions: &[&[u8]], + policy: AgentAddPolicy<'_>, + ask: bool, +) -> Result { + for pk in additions { + if pk.len() != 32 { + return Err(DbError::InvalidData(format!( + "pubkey must be 32 bytes, got {}", + pk.len() + ))); + } + } + + let mut tx = crate::begin_community_write_transaction( + pool, + community_id, + crate::observability::WriterOperation::EventWrite, + ) + .await?; + crate::channel_members::lock_channel_for_member_put(&mut tx, channel_id).await?; + + let members = locked_dm_members(tx.conn(), community_id, channel_id, actor).await?; + let stored: Option> = sqlx::query_scalar( + "SELECT participant_hash FROM channels WHERE community_id = $1 AND id = $2", + ) + .bind(community_id.as_uuid()) + .bind(channel_id) + .fetch_one(tx.conn()) + .await?; + + let mut added: Vec<&[u8]> = Vec::new(); + for pk in additions { + if !members.iter().any(|m| m == pk) && !added.contains(pk) { + added.push(pk); + } + } + + let mut grown: Vec<&[u8]> = members.iter().map(Vec::as_slice).collect(); + grown.extend(&added); + let agents = agents_among(tx.conn(), community_id, &grown).await?; + if count_people(&grown, &agents) > MAX_DM_PEOPLE { + return Err(DbError::InvalidData(format!( + "DM supports at most {MAX_DM_PEOPLE} people" + ))); + } + + // A DM of at most one person and their agents stays theirs: people + // joining it start a DM of everyone instead. + let current: Vec<&[u8]> = members.iter().map(Vec::as_slice).collect(); + if count_people(¤t, &agents) < 2 && count_people(&grown, &agents) >= 2 { + tx.rollback().await?; + return Ok(DmGrowth::PeopleStartNewDm); + } + let people_join = count_people(&grown, &agents) != count_people(¤t, &agents); + if ask && people_join { + tx.rollback().await?; + return Ok(DmGrowth::NeedsChoice); + } + + // The DM takes the grown set's identity: its people's, or all its members' + // when it has at most one person. If another DM has it, people meet there; + // agents join this DM in place, and it stops being any group's DM, since + // the identity it had no longer matches who is in it. + let hash = dm_identity_hash(&grown, &agents); + let moves = match &stored { + Some(stored) => stored.as_slice() != hash.as_slice(), + None => people_join, + }; + if moves && !claim_dm_identity(tx.conn(), community_id, channel_id, &hash).await? { + if people_join { + tx.rollback().await?; + return match find_dm_by_participants(pool, community_id, &hash).await? { + Some(existing) => existing_for(pool, community_id, existing.id, actor).await, + None => Err(DbError::InvalidData( + "a DM with these people already exists".to_string(), + )), + }; + } + sqlx::query( + "UPDATE channels SET participant_hash = NULL, updated_at = NOW() \ + WHERE community_id = $1 AND id = $2", + ) + .bind(community_id.as_uuid()) + .bind(channel_id) + .execute(tx.conn()) + .await?; + } + + // Checked only once they are sure to join this DM, not one of its people + // have elsewhere. + check_joining_agents(tx.conn(), community_id, actor, &added, policy).await?; + for pk in &added { + sqlx::query( + r#" + INSERT INTO channel_members (community_id, channel_id, pubkey, role, invited_by) + VALUES ($1, $2, $3, 'member', $4) + ON CONFLICT (community_id, channel_id, pubkey) DO UPDATE SET + sync_modified_at = clock_timestamp(), + removed_at = NULL, + removed_by = NULL, + hidden_at = NULL, + role = EXCLUDED.role + "#, + ) + .bind(community_id.as_uuid()) + .bind(channel_id) + .bind(*pk) + .bind(actor) + .execute(tx.conn()) + .await?; + } + + tx.commit().await?; + Ok(DmGrowth::Grown { + added: added.into_iter().map(<[u8]>::to_vec).collect(), + }) +} + +/// Start a DM of the people in the DM `source` plus `additions`, without its +/// history: what adding people to a DM does when they do not join it in place. +/// Agents already in `source` stay behind and can be added later; agents among +/// `additions` join, with `policy`'s permission. +/// +/// `source` must be a live, unarchived DM with `actor` as an active member. +/// Its members are read under its membership lock, held until the new DM is +/// made on the same transaction, so the new DM holds exactly who is in +/// `source` now. If a DM of these members already exists, found as +/// [`open_dm`] finds it (by its people with `by_people`, when people join), it +/// is returned to `actor` if they are in it, and shown in their sidebar; named +/// agents it lacks are the caller's to add. +/// +/// Returns `(channel, was_created, participants)`. +pub async fn fork_dm( + pool: &PgPool, + community_id: CommunityId, + source: Uuid, + actor: &[u8], + additions: &[&[u8]], + by_people: bool, + policy: AgentAddPolicy<'_>, +) -> Result<(ChannelRecord, bool, Vec>)> { + let mut tx = crate::begin_community_write_transaction( + pool, + community_id, + crate::observability::WriterOperation::EventWrite, + ) + .await?; + crate::channel_members::lock_channel_for_member_put(&mut tx, source).await?; + let source_members = locked_dm_members(tx.conn(), community_id, source, actor).await?; + let source_refs: Vec<&[u8]> = source_members.iter().map(Vec::as_slice).collect(); + let agents = agents_among(tx.conn(), community_id, &source_refs).await?; + let added_agents = agents_among(tx.conn(), community_id, additions).await?; + // Agents alone do not change who the DM is for, so they start a DM of + // exactly these members, as they always have. + let people_join = additions + .iter() + .any(|pk| !added_agents.contains(*pk) && !source_members.iter().any(|m| m == pk)); + let mut members: Vec> = source_members + .into_iter() + .filter(|pk| pk.as_slice() == actor || !agents.contains(pk)) + .collect(); + for pk in additions { + if !members.iter().any(|m| m == pk) { + members.push(pk.to_vec()); + } + } + let refs: Vec<&[u8]> = members.iter().map(Vec::as_slice).collect(); + let (channel, created) = find_or_create_dm( + tx.conn(), + community_id, + &refs, + actor, + by_people && people_join, + policy, + ) + .await?; + if !created { + let shown = sqlx::query( + "UPDATE channel_members SET hidden_at = NULL \ + WHERE community_id = $1 AND channel_id = $2 AND pubkey = $3 AND removed_at IS NULL", + ) + .bind(community_id.as_uuid()) + .bind(channel.id) + .bind(actor) + .execute(tx.conn()) + .await?; + if shown.rows_affected() == 0 { + return Err(DbError::AccessDenied( + "a DM with these people already exists".to_string(), + )); + } + } + tx.commit().await?; + Ok((channel, created, members)) +} + +/// The active members of `channel_id`, read under its membership lock, after +/// checking that it is a live, unarchived DM and that `actor` is one of them. +async fn locked_dm_members( + conn: &mut sqlx::PgConnection, + community_id: CommunityId, + channel_id: Uuid, + actor: &[u8], +) -> Result>> { + let channel = sqlx::query( + "SELECT channel_type::text AS channel_type, archived_at FROM channels \ + WHERE community_id = $1 AND id = $2 AND deleted_at IS NULL", + ) + .bind(community_id.as_uuid()) + .bind(channel_id) + .fetch_optional(&mut *conn) + .await? + .ok_or(DbError::ChannelNotFound(channel_id))?; + let channel_type: String = channel.try_get("channel_type")?; + if channel_type != "dm" { + return Err(DbError::InvalidData("channel is not a DM".to_string())); + } + if channel + .try_get::>, _>("archived_at")? + .is_some() + { + return Err(DbError::AccessDenied("DM is archived".to_string())); + } + let members: Vec> = sqlx::query_scalar( + "SELECT pubkey FROM channel_members \ + WHERE community_id = $1 AND channel_id = $2 AND removed_at IS NULL", + ) + .bind(community_id.as_uuid()) + .bind(channel_id) + .fetch_all(&mut *conn) + .await?; + if !members.iter().any(|m| m == actor) { + return Err(DbError::AccessDenied("not a member of this DM".to_string())); + } + Ok(members) +} + +/// Give `channel_id` the identity `hash` unless another live channel has it. +/// Returns whether it did. Runs under the DM's membership lock. +async fn claim_dm_identity( + conn: &mut sqlx::PgConnection, + community_id: CommunityId, + channel_id: Uuid, + hash: &[u8], +) -> Result { + let taken = sqlx::query_scalar::<_, Uuid>( + "SELECT id FROM channels \ + WHERE community_id = $1 AND participant_hash = $2 AND id <> $3 \ + AND deleted_at IS NULL", + ) + .bind(community_id.as_uuid()) + .bind(hash) + .bind(channel_id) + .fetch_optional(&mut *conn) + .await?; + if taken.is_some() { + return Ok(false); + } + // A savepoint, so losing the claim to a DM created or grown into the same + // identity since the check above leaves the transaction usable. + let mut claim = sqlx::Connection::begin(&mut *conn).await?; + let moved = sqlx::query( + "UPDATE channels SET participant_hash = $3, updated_at = NOW() \ + WHERE community_id = $1 AND id = $2", + ) + .bind(community_id.as_uuid()) + .bind(channel_id) + .bind(hash) + .execute(&mut *claim) + .await; + match moved { + Err(sqlx::Error::Database(e)) if e.code().as_deref() == Some("23505") => { + claim.rollback().await?; + Ok(false) + } + moved => { + moved?; + claim.commit().await?; + Ok(true) + } + } +} + +/// Keep `channel_id`'s fingerprint, if it is a DM, true to who is still in it +/// after `removed` left or was removed. When a person left, the DM stops being +/// any group's DM: it keeps its history for those still in it, and opening +/// that group again starts a new DM. When an agent left a DM of two or more +/// people, its people are unchanged, so it stays (or, if it was identified by +/// all its members, becomes) their DM, unless they already have another, in +/// which case it stops being any group's DM. The caller holds the channel's +/// membership lock, as every membership writer does, so this cannot race +/// [`grow_dm`]. +pub(crate) async fn release_dm_identity( + conn: &mut sqlx::PgConnection, + community_id: CommunityId, + channel_id: Uuid, + removed: &[u8], +) -> Result<()> { + let stored: Option> = sqlx::query_scalar( + "SELECT participant_hash FROM channels \ + WHERE community_id = $1 AND id = $2 AND channel_type = 'dm'", + ) + .bind(community_id.as_uuid()) + .bind(channel_id) + .fetch_optional(&mut *conn) + .await? + .flatten(); + let Some(stored) = stored else { + return Ok(()); + }; + let members: Vec> = sqlx::query_scalar( + "SELECT pubkey FROM channel_members \ + WHERE community_id = $1 AND channel_id = $2 AND removed_at IS NULL", + ) + .bind(community_id.as_uuid()) + .bind(channel_id) + .fetch_all(&mut *conn) + .await?; + let mut members: Vec<&[u8]> = members.iter().map(Vec::as_slice).collect(); + members.push(removed); + let agents = agents_among(&mut *conn, community_id, &members).await?; + members.pop(); + let hash = dm_identity_hash(&members, &agents); + if hash.as_slice() == stored.as_slice() { + return Ok(()); + } + if agents.contains(removed) + && count_people(&members, &agents) >= 2 + && claim_dm_identity(&mut *conn, community_id, channel_id, &hash).await? + { + return Ok(()); + } + sqlx::query( + "UPDATE channels SET participant_hash = NULL \ + WHERE community_id = $1 AND id = $2", + ) + .bind(community_id.as_uuid()) + .bind(channel_id) + .execute(&mut *conn) + .await?; + Ok(()) +} + +/// [`DmGrowth::Existing`] for `actor`, who must be an active member of that +/// DM: growing a DM must not reveal a DM the actor is not in. +async fn existing_for( + pool: &PgPool, + community_id: CommunityId, + existing: Uuid, + actor: &[u8], +) -> Result { + if crate::channel_members::is_member(pool, community_id, existing, actor).await? { + Ok(DmGrowth::Existing(existing)) + } else { + Err(DbError::AccessDenied( + "a DM with these people already exists".to_string(), + )) } - Ok((channel, was_created)) } // -- Hide / unhide ------------------------------------------------------------ @@ -560,8 +1224,18 @@ impl Db { community_id: CommunityId, participants: &[&[u8]], created_by: &[u8], - ) -> Result { - crate::dm::create_dm(&self.pool, community_id, participants, created_by).await + by_people: bool, + policy: AgentAddPolicy<'_>, + ) -> Result<(ChannelRecord, bool)> { + crate::dm::create_dm( + &self.pool, + community_id, + participants, + created_by, + by_people, + policy, + ) + .await } /// Create or reuse a DM without unhiding it; true only for the creator. @@ -594,8 +1268,65 @@ impl Db { community_id: CommunityId, pubkeys: &[&[u8]], created_by: &[u8], + by_people: bool, + policy: AgentAddPolicy<'_>, ) -> Result<(ChannelRecord, bool)> { - crate::dm::open_dm(&self.pool, community_id, pubkeys, created_by).await + crate::dm::open_dm( + &self.pool, + community_id, + pubkeys, + created_by, + by_people, + policy, + ) + .await + } + + /// Add members to a DM in place, keeping its history. + #[datastore_span(name = "grow_dm", system = "postgresql")] + pub async fn grow_dm( + &self, + community_id: CommunityId, + channel_id: Uuid, + actor: &[u8], + additions: &[&[u8]], + policy: AgentAddPolicy<'_>, + ask: bool, + ) -> Result { + crate::dm::grow_dm( + &self.pool, + community_id, + channel_id, + actor, + additions, + policy, + ask, + ) + .await + } + + /// Start a DM of everyone in a DM plus `additions`, without its history, + /// or return the DM they already have. + #[datastore_span(name = "fork_dm", system = "postgresql")] + pub async fn fork_dm( + &self, + community_id: CommunityId, + source: Uuid, + actor: &[u8], + additions: &[&[u8]], + by_people: bool, + policy: AgentAddPolicy<'_>, + ) -> Result<(ChannelRecord, bool, Vec>)> { + crate::dm::fork_dm( + &self.pool, + community_id, + source, + actor, + additions, + by_people, + policy, + ) + .await } /// Hide a DM channel for a specific user. @@ -636,6 +1367,10 @@ impl Db { // -- Tests -------------------------------------------------------------------- +#[cfg(test)] +#[path = "dm_postgres_tests.rs"] +mod postgres_tests; + #[cfg(test)] mod tests { use super::*; @@ -675,7 +1410,3 @@ mod tests { assert_eq!(h.len(), 32); } } - -#[cfg(test)] -#[path = "dm_postgres_tests.rs"] -mod postgres_tests; diff --git a/crates/buzz-db/src/store/dm_postgres_tests.rs b/crates/buzz-db/src/store/dm_postgres_tests.rs index 9b1fe1d2ba..fa4626c646 100644 --- a/crates/buzz-db/src/store/dm_postgres_tests.rs +++ b/crates/buzz-db/src/store/dm_postgres_tests.rs @@ -3,6 +3,8 @@ use crate::CreateCommunityWithOwnerResult; use sqlx::postgres::PgPoolOptions; use std::time::Duration; +const ALLOW: AgentAddPolicy<'static> = &|_: &str, _: &[u8]| Ok(()); + #[tokio::test] #[ignore = "requires Postgres"] async fn cluster_global_concurrent_dm_creation_reports_only_the_inserter() { @@ -56,14 +58,21 @@ async fn cluster_global_concurrent_dm_creation_reports_only_the_inserter() { .await .expect("block inserts, allow lookups"); let first_pool = first.clone(); - let first_task = - tokio::spawn( - async move { open_dm(&first_pool, community, &[&recipient], &author).await }, - ); + let first_task = tokio::spawn(async move { + open_dm(&first_pool, community, &[&recipient], &author, false, ALLOW).await + }); let second_pool = second.clone(); let second_task = tokio::spawn(async move { if second_is_interactive { - open_dm(&second_pool, community, &[&recipient], &author).await + open_dm( + &second_pool, + community, + &[&recipient], + &author, + false, + ALLOW, + ) + .await } else { create_dm_if_missing(&second_pool, community, &[&author, &recipient], &author).await } @@ -123,7 +132,7 @@ async fn cluster_global_concurrent_dm_creation_reports_only_the_inserter() { .expect("hidden DMs") .contains(&reused.id)); let (reopened, created) = db - .open_dm(community, &[&recipient], &author) + .open_dm(community, &[&recipient], &author, false, ALLOW) .await .expect("interactive reuse"); assert_eq!(reopened.id, reused.id); diff --git a/crates/buzz-db/src/store/relay_admin_actions.rs b/crates/buzz-db/src/store/relay_admin_actions.rs index fc2fb32c98..94403512b4 100644 --- a/crates/buzz-db/src/store/relay_admin_actions.rs +++ b/crates/buzz-db/src/store/relay_admin_actions.rs @@ -736,6 +736,7 @@ pub async fn execute_kick_with_marker( tx.rollback().await?; return Ok(KickWithMarkerResult::AlreadyGone); } + crate::dm::release_dm_identity(tx.conn(), community_id, channel_id, target_pubkey).await?; let marker = sqlx::query( r#" @@ -1742,6 +1743,9 @@ pub async fn deploy_kick_member( .bind(target_pubkey) .execute(tx.conn()) .await?; + if result.rows_affected() > 0 { + crate::dm::release_dm_identity(tx.conn(), community_id, channel_id, target_pubkey).await?; + } tx.commit().await?; if result.rows_affected() > 0 { diff --git a/crates/buzz-relay/src/handlers/command_executor.rs b/crates/buzz-relay/src/handlers/command_executor.rs index 4c6eef3489..f7710f759a 100644 --- a/crates/buzz-relay/src/handlers/command_executor.rs +++ b/crates/buzz-relay/src/handlers/command_executor.rs @@ -9,6 +9,7 @@ //! 3. Pubkey/auth identity match //! 4. Per-kind scope authorization +use std::collections::HashMap; use std::sync::Arc; use chrono::Utc; @@ -20,6 +21,7 @@ use uuid::Uuid; use buzz_core::kind::*; use buzz_core::tenant::{CommunityId, TenantContext}; use buzz_datastore_tracing::datastore_span; +use buzz_db::dm::{DmGrowth, MAX_DM_PEOPLE}; use buzz_db::workflow::{ApprovalStatus, RunStatus}; use buzz_db::DbError; use buzz_workflow::executor::TriggerContext; @@ -291,6 +293,191 @@ fn compute_definition_hash(json_str: &str) -> Vec { Sha256::digest(json_str.as_bytes()).to_vec() } +/// Map a DM write's refusal to the client's error. +fn dm_write_error(e: DbError) -> IngestError { + match e { + DbError::AccessDenied(m) => IngestError::Rejected(format!("forbidden: {m}")), + DbError::InvalidData(m) => IngestError::Rejected(format!("invalid: {m}")), + DbError::ChannelNotFound(_) => IngestError::Rejected("invalid: DM not found".into()), + e => IngestError::Internal(format!("error: db: {e}")), + } +} + +/// The side effects of members joining an existing DM (post-commit, +/// best-effort): membership caches, a `member_joined` system message each, +/// kind:39000/39002 and kind:44100. +async fn announce_dm_additions( + tenant: &TenantContext, + state: &Arc, + channel_id: Uuid, + actor: &[u8], + added: &[Vec], +) { + if added.is_empty() { + return; + } + for pk in added { + state.invalidate_membership(tenant, channel_id, pk); + } + let actor_hex = hex::encode(actor); + for pk in added { + if let Err(e) = emit_system_message( + tenant, + state, + channel_id, + serde_json::json!({ + "type": "member_joined", + "actor": actor_hex, + "target": hex::encode(pk), + }), + chrono::Utc::now(), + ) + .await + { + warn!("DM add: system message failed: {e}"); + } + } + if let Err(e) = emit_group_discovery_events(tenant, state, channel_id).await { + warn!(channel = %channel_id, "DM add: discovery emission failed: {e}"); + } + for pk in added { + if let Err(e) = emit_membership_notification( + tenant, + state, + channel_id, + pk, + actor, + KIND_MEMBER_ADDED_NOTIFICATION, + ) + .await + { + warn!("DM add: membership notification failed: {e}"); + } + } +} + +/// The side effects of a newly created DM (post-commit, best-effort). +async fn announce_dm_created( + tenant: &TenantContext, + state: &Arc, + channel_id: Uuid, + actor: &[u8], + participants: &[Vec], +) { + metrics::counter!( + "buzz_channels_created_total", + "community" => tenant.host().to_owned(), + "type" => "dm" + ) + .increment(1); + + for pk in participants { + state.invalidate_membership(tenant, channel_id, pk); + } + + let participant_hexes: Vec = participants.iter().map(hex::encode).collect(); + if let Err(e) = emit_system_message( + tenant, + state, + channel_id, + serde_json::json!({ + "type": "dm_created", + "actor": hex::encode(actor), + "participants": participant_hexes, + }), + chrono::Utc::now(), + ) + .await + { + warn!("DM open: system message failed: {e}"); + } + + if let Err(e) = emit_group_discovery_events(tenant, state, channel_id).await { + warn!(channel = %channel_id, "DM open: discovery emission failed: {e}"); + } + + for participant in participants { + if let Err(e) = emit_membership_notification( + tenant, + state, + channel_id, + participant, + actor, + KIND_MEMBER_ADDED_NOTIFICATION, + ) + .await + { + warn!("DM open: membership notification failed: {e}"); + } + } +} + +/// A DM command's `history` tag. +#[derive(Clone, Copy, PartialEq, Eq)] +enum History { + /// No tag: DM commands behave as before members could join in place. + Untagged, + /// `["history", "include"]`: the caller has agreed to share an existing + /// DM's history with whoever joins it. + Include, + /// `["history", "ask"]` (kind:41011 only): join as with `include` when the + /// relay needs no choice, and refuse with [`NEEDS_HISTORY_CHOICE`] when + /// people would join a DM of two or more people. + Ask, +} + +fn history_tag(event: &Event, ask_allowed: bool) -> Result { + match extract_tag(event, "history").as_deref() { + None => Ok(History::Untagged), + Some("include") => Ok(History::Include), + Some("ask") if ask_allowed => Ok(History::Ask), + Some(other) => Err(IngestError::Rejected(format!( + "invalid: history must be \"include\", got \"{other}\"" + ))), + } +} + +/// Why an add tagged `["history", "ask"]` was refused: people would join a DM +/// of two or more people, so the caller must choose whether they see its +/// history and send the add again tagged `include`, or untagged. Clients +/// match this exact text. +const NEEDS_HISTORY_CHOICE: &str = "needs-choice: history"; + +/// Why the relay's moderation DM cannot take anyone else. +const MODERATION_DM_REFUSAL: &str = "invalid: this DM cannot be changed"; + +/// Why an agent cannot send the history tag: only people choose to share a +/// DM's history, or which DM their people share. +const ONLY_PEOPLE_SHARE_HISTORY: &str = "forbidden: only people can share a DM's history"; + +/// The agents among `pubkeys` (users with an owner): each one's +/// `channel_add_policy` and owner. +async fn dm_agents( + tenant: &TenantContext, + state: &Arc, + pubkeys: &[Vec], +) -> Result, (String, Vec)>, IngestError> { + let policies = state + .db + .get_agent_channel_policies(tenant.community(), pubkeys) + .await + .map_err(|e| IngestError::Internal(format!("error: agent lookup: {e}")))?; + Ok(policies + .into_iter() + .filter_map(|(pubkey, (policy, owner))| owner.map(|owner| (pubkey, (policy, owner)))) + .collect()) +} + +/// Whether `actor` may put an agent, given its `channel_add_policy` and +/// owner, in a DM with others, as a kind:9000 add would decide. The DM writes +/// apply it to the agents actually joining, under the DM's lock. +fn agent_add_policy(actor: &[u8]) -> impl Fn(&str, &[u8]) -> Result<(), String> + Sync + '_ { + move |policy, owner| { + super::channel_authz::decide_channel_add_policy(policy, Some(owner), actor) + .map_err(|e| e.to_string()) + } +} + async fn handle_dm_open( tenant: &TenantContext, state: &Arc, @@ -298,35 +485,47 @@ async fn handle_dm_open( auth: &IngestAuth, ) -> Result { let self_bytes = auth.pubkey().to_bytes().to_vec(); - let self_hex = hex::encode(&self_bytes); + let include_history = history_tag(event, false)? == History::Include; - // 1. Extract participant pubkeys from `p` tags - let p_tags = extract_p_tags(event); - - // 2. Validate: at least 1 other participant, max 8 others (9 total) - if p_tags.is_empty() { + // 1. Decode the other participants from `p` tags (deduplicated). + let mut others: Vec> = Vec::new(); + for hex_str in &extract_p_tags(event) { + let pk = decode_pubkey(hex_str)?; + if pk != self_bytes && !others.contains(&pk) { + others.push(pk); + } + } + if others.is_empty() { return Err(IngestError::Rejected( "invalid: pubkeys must contain at least 1 other participant".into(), )); } - if p_tags.len() > 8 { - return Err(IngestError::Rejected( - "invalid: pubkeys may contain at most 8 other participants (9 total)".into(), - )); - } - // Decode all provided pubkeys - let mut other_bytes: Vec> = Vec::with_capacity(p_tags.len()); - for hex_str in &p_tags { - other_bytes.push(decode_pubkey(hex_str)?); + // 2. The relay's moderation DM stays two-party. At most 9 people, the + // caller included; agents do not count. Only people share a DM's + // history. + let relay_pubkey = state.relay_keypair.public_key().to_bytes(); + if others.len() > 1 + && others + .iter() + .any(|pk| pk.as_slice() == relay_pubkey.as_slice()) + { + return Err(IngestError::Rejected(MODERATION_DM_REFUSAL.into())); } - - // 3. Build full participant set (self + others, deduplicated) let mut all_bytes: Vec> = vec![self_bytes.clone()]; - for ob in &other_bytes { - if !all_bytes.iter().any(|b| b == ob) { - all_bytes.push(ob.clone()); - } + all_bytes.extend(others); + let agents = dm_agents(tenant, state, &all_bytes).await?; + let people = all_bytes + .iter() + .filter(|pk| !agents.contains_key(*pk)) + .count(); + if people > MAX_DM_PEOPLE { + return Err(IngestError::Rejected(format!( + "invalid: a DM may hold at most {MAX_DM_PEOPLE} people; agents do not count" + ))); + } + if include_history && agents.contains_key(&self_bytes) { + return Err(IngestError::Rejected(ONLY_PEOPLE_SHARE_HISTORY.into())); } // Persist the command event (idempotency) — returns open transaction @@ -341,77 +540,49 @@ async fn handle_dm_open( PersistResult::Inserted(tx) => tx, }; - // 4. Execute: open_dm + // 3. Execute. With history, open the DM of these people, bring it up to + // date and add any named agents it does not hold yet; without, the DM of + // exactly these members or, for people alone, their DM, which agents may + // have joined. Each agent that joins needs its policy. Only + // agents join a reopened DM: someone who left is not added back. let all_refs: Vec<&[u8]> = all_bytes.iter().map(|b| b.as_slice()).collect(); + let policy = agent_add_policy(&self_bytes); let (channel, was_created) = state .db - .open_dm(tenant.community(), &all_refs, &self_bytes) + .open_dm( + tenant.community(), + &all_refs, + &self_bytes, + include_history, + &policy, + ) .await - .map_err(|e| IngestError::Internal(format!("error: db open_dm: {e}")))?; + .map_err(dm_write_error)?; + let added = if was_created || !include_history { + Vec::new() + } else { + let named_agents: Vec> = agents.into_keys().collect(); + grow_with_agents(tenant, state, channel.id, &self_bytes, &named_agents).await? + }; // Finalize the idempotency record after the separate mutation succeeds. tx.commit() .await .map_err(|e| IngestError::Internal(format!("error: commit transaction: {e}")))?; - // 5. Side effects if newly created (post-commit, best-effort) + // 4. Side effects (post-commit, best-effort) if was_created { - metrics::counter!( - "buzz_channels_created_total", - "community" => tenant.host().to_owned(), - "type" => "dm" - ) - .increment(1); - - // Invalidate caches for all participants - for pk in &all_bytes { - state.invalidate_membership(tenant, channel.id, pk); - } - - let participant_hexes: Vec = all_bytes.iter().map(hex::encode).collect(); - if let Err(e) = emit_system_message( - tenant, - state, - channel.id, - serde_json::json!({ - "type": "dm_created", - "actor": self_hex, - "participants": participant_hexes, - }), - chrono::Utc::now(), - ) - .await - { - warn!("DM open: system message failed: {e}"); - } - - if let Err(e) = emit_group_discovery_events(tenant, state, channel.id).await { - warn!(channel = %channel.id, "DM open: discovery emission failed: {e}"); - } - - for participant in &all_bytes { - if let Err(e) = emit_membership_notification( - tenant, - state, - channel.id, - participant, - &self_bytes, - KIND_MEMBER_ADDED_NOTIFICATION, - ) - .await - { - warn!("DM open: membership notification failed: {e}"); - } - } + announce_dm_created(tenant, state, channel.id, &self_bytes, &all_bytes).await; } else { // Re-open of an existing DM cleared the caller's hidden_at; refresh // their NIP-DV snapshot so the DM reappears in the sidebar. if let Err(e) = publish_dm_visibility_snapshot(tenant, state, &self_bytes).await { warn!("DM re-open: visibility snapshot failed: {e}"); } + announce_dm_additions(tenant, state, channel.id, &self_bytes, &added).await; } - // 6. Return response + // 5. Return response Ok(IngestResult { event_id: event.id.to_hex(), accepted: true, @@ -425,6 +596,46 @@ async fn handle_dm_open( }) } +/// Bring the existing DM `channel_id` up to date and add `agents` to it in +/// place. Only people joining change which DM it is, so it cannot turn out to +/// be another one. +async fn grow_with_agents( + tenant: &TenantContext, + state: &Arc, + channel_id: Uuid, + actor: &[u8], + agents: &[Vec], +) -> Result>, IngestError> { + let refs: Vec<&[u8]> = agents.iter().map(Vec::as_slice).collect(); + let policy = agent_add_policy(actor); + match state + .db + .grow_dm(tenant.community(), channel_id, actor, &refs, &policy, false) + .await + .map_err(dm_write_error)? + { + DmGrowth::Grown { added } => Ok(added), + DmGrowth::Existing(_) | DmGrowth::PeopleStartNewDm | DmGrowth::NeedsChoice => Err( + IngestError::Internal("error: adding agents changed the DM's people".into()), + ), + } +} + +/// kind:41011: add people and agents to a DM. +/// +/// With `["history", "include"]`, people and agents join in place, with the +/// DM's history. People move the DM's identity to the grown set of people, or, +/// if a DM of those people already exists, that DM is returned instead and +/// named agents join it there. People added to a DM of at most one person +/// start a new DM of its people and the additions (no history), or land in +/// the DM those people already have, which named agents join. Without the +/// tag, as older clients send, the add finds the DM of exactly this DM's +/// people and the additions (for people alone, their DM, which agents may +/// have joined) or makes one, and adds no one to an existing DM. With +/// `["history", "ask"]`, the relay adds agents alone and people to a DM of at +/// most one person as with `include`, and refuses people joining any other +/// DM with [`NEEDS_HISTORY_CHOICE`], changing nothing. An agent cannot send +/// either tag. async fn handle_dm_add_member( tenant: &TenantContext, state: &Arc, @@ -445,6 +656,8 @@ async fn handle_dm_add_member( "invalid: must specify at least 1 new participant in p tags".into(), )); } + let history = history_tag(event, true)?; + let include_history = history != History::Untagged; // 2. Validate caller is member of existing DM let is_member = state @@ -467,28 +680,41 @@ async fn handle_dm_add_member( return Err(IngestError::Rejected("invalid: channel is not a DM".into())); } - // 4. Get existing members, merge with new - let existing_members = state + // 4. Read the current members. The relay's moderation DM stays two-party, + // and the relay joins no other DM. + let members: Vec> = state .db .get_members_for_event_write(tenant.community(), channel_id) .await - .map_err(|e| IngestError::Internal(format!("error: get members: {e}")))?; - - let mut all_bytes: Vec> = existing_members.into_iter().map(|m| m.pubkey).collect(); - - // Decode and merge new pubkeys - for hex_str in &p_tags { - let bytes = decode_pubkey(hex_str)?; - if !all_bytes.iter().any(|b| b == &bytes) { - all_bytes.push(bytes); - } + .map_err(|e| IngestError::Internal(format!("error: get members: {e}")))? + .into_iter() + .map(|m| m.pubkey) + .collect(); + let relay_pubkey = state.relay_keypair.public_key().to_bytes(); + if members + .iter() + .any(|m| m.as_slice() == relay_pubkey.as_slice()) + { + return Err(IngestError::Rejected(MODERATION_DM_REFUSAL.into())); } - // 5. Enforce max 9 participants - if all_bytes.len() > 9 { - return Err(IngestError::Rejected( - "invalid: DM supports at most 9 participants".into(), - )); + let mut additions: Vec> = Vec::new(); + for hex_str in &p_tags { + let pk = decode_pubkey(hex_str)?; + if pk.as_slice() == relay_pubkey.as_slice() { + return Err(IngestError::Rejected(MODERATION_DM_REFUSAL.into())); + } + // Keep members named here: an agent in this DM still joins the DM the + // add lands in. The write leaves out whoever is already there. + if !additions.contains(&pk) { + additions.push(pk); + } + } + let actor_is_agent = !dm_agents(tenant, state, std::slice::from_ref(&self_bytes)) + .await? + .is_empty(); + if include_history && actor_is_agent { + return Err(IngestError::Rejected(ONLY_PEOPLE_SHARE_HISTORY.into())); } // Persist the command event — returns open transaction @@ -503,60 +729,112 @@ async fn handle_dm_add_member( PersistResult::Inserted(tx) => tx, }; - // 6. Execute: open_dm with expanded set (creates NEW DM — DM sets are immutable) - let all_refs: Vec<&[u8]> = all_bytes.iter().map(|b| b.as_slice()).collect(); - let (new_channel, was_created) = state - .db - .open_dm(tenant.community(), &all_refs, &self_bytes) - .await - .map_err(|e| IngestError::Internal(format!("error: db open_dm: {e}")))?; + // 5. Execute. Each write reads the DM's members under its lock and checks + // the agents that actually join. + let addition_refs: Vec<&[u8]> = additions.iter().map(Vec::as_slice).collect(); + let policy = agent_add_policy(&self_bytes); + let growth = if include_history { + // Grow this DM in place. + Some( + state + .db + .grow_dm( + tenant.community(), + channel_id, + &self_bytes, + &addition_refs, + &policy, + history == History::Ask, + ) + .await + .map_err(dm_write_error)?, + ) + } else { + None + }; + let (target, was_created, added, moved_elsewhere, participants) = match growth { + // Dropping `tx` uncommitted forgets this command, so the add can be + // sent again with the caller's choice. + Some(DmGrowth::NeedsChoice) => { + return Err(IngestError::Rejected(NEEDS_HISTORY_CHOICE.into())); + } + Some(DmGrowth::Grown { added }) => (channel_id, false, added, false, Vec::new()), + // These people already have a DM: the agents join them there. + Some(DmGrowth::Existing(other)) => { + let agents: Vec> = dm_agents(tenant, state, &additions) + .await? + .into_keys() + .collect(); + let added = grow_with_agents(tenant, state, other, &self_bytes, &agents).await?; + (other, false, added, true, Vec::new()) + } + // Start a new DM of its people and the additions (no history); this + // DM and its agents stay put. A DM of at most one person never gains + // people, even with the tag. With the tag (sent only by people), if + // those people already have a DM, the caller lands there, and named + // agents join it with its history, as agents do. Without it, as older + // clients send, the add finds or makes a DM of exactly these members + // and puts no one into a DM they weren't already in. + Some(DmGrowth::PeopleStartNewDm) | None => { + let (channel, created, participants) = state + .db + .fork_dm( + tenant.community(), + channel_id, + &self_bytes, + &addition_refs, + include_history, + &policy, + ) + .await + .map_err(dm_write_error)?; + let added = if created || !include_history { + Vec::new() + } else { + let agents: Vec> = dm_agents(tenant, state, &additions) + .await? + .into_keys() + .collect(); + grow_with_agents(tenant, state, channel.id, &self_bytes, &agents).await? + }; + (channel.id, created, added, !created, participants) + } + }; // Finalize the idempotency record after the separate mutation succeeds. tx.commit() .await .map_err(|e| IngestError::Internal(format!("error: commit transaction: {e}")))?; - // 7. Cache invalidation + notifications for new DM (post-commit, best-effort) + // 6. Side effects (post-commit, best-effort) if was_created { - metrics::counter!( - "buzz_channels_created_total", - "community" => tenant.host().to_owned(), - "type" => "dm" - ) - .increment(1); - - for pk in &all_bytes { - state.invalidate_membership(tenant, new_channel.id, pk); - } - - if let Err(e) = emit_group_discovery_events(tenant, state, new_channel.id).await { - warn!(channel = %new_channel.id, "DM add_member: discovery emission failed: {e}"); - } - - for participant_bytes in &all_bytes { - if let Err(e) = emit_membership_notification( - tenant, - state, - new_channel.id, - participant_bytes, - &self_bytes, - KIND_MEMBER_ADDED_NOTIFICATION, - ) - .await + announce_dm_created(tenant, state, target, &self_bytes, &participants).await; + } else { + if moved_elsewhere { + // The caller lands in an existing DM; make sure they can see it. + if let Err(e) = state + .db + .unhide_dm(tenant.community(), target, &self_bytes) + .await { - warn!("DM add_member: membership notification failed: {e}"); + warn!("DM add: unhide failed: {e}"); + } else if let Err(e) = publish_dm_visibility_snapshot(tenant, state, &self_bytes).await + { + warn!("DM add: visibility snapshot failed: {e}"); } } + announce_dm_additions(tenant, state, target, &self_bytes, &added).await; } - // 8. Return response + // 7. Return response Ok(IngestResult { event_id: event.id.to_hex(), accepted: true, message: format!( "response:{}", serde_json::json!({ - "channel_id": new_channel.id.to_string(), + "channel_id": target.to_string(), + "created": was_created, }) ), }) diff --git a/crates/buzz-relay/src/handlers/dm_growth_postgres_tests.rs b/crates/buzz-relay/src/handlers/dm_growth_postgres_tests.rs new file mode 100644 index 0000000000..965f482c07 --- /dev/null +++ b/crates/buzz-relay/src/handlers/dm_growth_postgres_tests.rs @@ -0,0 +1,1775 @@ +//! Postgres-backed tests for growing a DM: kind:41011 adding people in place +//! (`["history", "include"]`) or into a new DM, agents joining without +//! changing which DM it is, and kind:41010 finding a DM by its people. + +use std::sync::Arc; + +use buzz_core::TenantContext; +use nostr::{EventBuilder, Keys, Kind, Tag}; +use uuid::Uuid; + +use super::group_state_postgres_tests::{community, http_auth, state}; +use crate::handlers::ingest::{ingest_event, IngestError, IngestResult}; +use crate::state::AppState; + +fn hex(keys: &Keys) -> String { + keys.public_key().to_hex() +} + +async fn submit( + state: &Arc, + tenant: &TenantContext, + actor: &Keys, + kind: u16, + tags: Vec>, +) -> Result { + let tags: Vec = tags + .into_iter() + .map(|tag| Tag::parse(tag).expect("tag")) + // A unique tag so identical commands are distinct events. + .chain([Tag::parse(["client", &Uuid::new_v4().to_string()]).expect("tag")]) + .collect(); + let event = EventBuilder::new(Kind::Custom(kind), "") + .tags(tags) + .sign_with_keys(actor) + .expect("sign"); + ingest_event(state, tenant, event, http_auth(actor)).await +} + +fn response_channel(result: &IngestResult) -> (Uuid, bool) { + let json: serde_json::Value = serde_json::from_str( + result + .message + .strip_prefix("response:") + .unwrap_or_else(|| panic!("no response in {:?}", result.message)), + ) + .expect("response json"); + ( + json["channel_id"] + .as_str() + .expect("channel_id") + .parse() + .expect("uuid"), + json["created"].as_bool().expect("created"), + ) +} + +async fn open( + state: &Arc, + tenant: &TenantContext, + actor: &Keys, + others: &[&Keys], +) -> Result { + open_tagged(state, tenant, actor, others, false).await +} + +/// Open a DM with `others`, agreeing to share an existing DM's history. +async fn open_with_history( + state: &Arc, + tenant: &TenantContext, + actor: &Keys, + others: &[&Keys], +) -> Result { + open_tagged(state, tenant, actor, others, true).await +} + +async fn open_tagged( + state: &Arc, + tenant: &TenantContext, + actor: &Keys, + others: &[&Keys], + history: bool, +) -> Result { + let mut tags: Vec> = others.iter().map(|k| vec!["p".into(), hex(k)]).collect(); + if history { + tags.push(vec!["history".into(), "include".into()]); + } + submit(state, tenant, actor, 41010, tags) + .await + .map(|r| response_channel(&r).0) +} + +async fn add( + state: &Arc, + tenant: &TenantContext, + actor: &Keys, + dm: Uuid, + others: &[&Keys], + include_history: bool, +) -> Result<(Uuid, bool), IngestError> { + let mut tags: Vec> = vec![vec!["h".into(), dm.to_string()]]; + tags.extend(others.iter().map(|k| vec!["p".into(), hex(k)])); + if include_history { + tags.push(vec!["history".into(), "include".into()]); + } + submit(state, tenant, actor, 41011, tags) + .await + .map(|r| response_channel(&r)) +} + +async fn members(state: &AppState, tenant: &TenantContext, dm: Uuid) -> Vec { + let mut members: Vec = state + .db + .get_members(tenant.community(), dm) + .await + .expect("members") + .into_iter() + .map(|m| ::hex::encode(m.pubkey)) + .collect(); + members.sort(); + members +} + +fn set_of(keys: &[&Keys]) -> Vec { + let mut set: Vec = keys.iter().map(|k| hex(k)).collect(); + set.sort(); + set +} + +/// Make `agent` an agent owned by `owner`, with `policy` for third-party adds. +async fn make_agent( + state: &AppState, + tenant: &TenantContext, + agent: &Keys, + owner: &Keys, + policy: &str, +) { + let agent_bytes = agent.public_key().to_bytes(); + let owner_bytes = owner.public_key().to_bytes(); + for pk in [&agent_bytes, &owner_bytes] { + state + .db + .ensure_user(tenant.community(), pk) + .await + .expect("user"); + } + state + .db + .set_agent_owner(tenant.community(), &agent_bytes, &owner_bytes) + .await + .expect("owner"); + state + .db + .set_channel_add_policy(tenant.community(), &agent_bytes, policy) + .await + .expect("policy"); +} + +fn rejected(result: Result, needle: &str) { + match result { + Err(IngestError::Rejected(message)) => { + assert!(message.contains(needle), "{message:?} lacks {needle:?}") + } + other => panic!("expected a refusal containing {needle:?}, got {other:?}"), + } +} + +/// Adding a person with history keeps the DM and moves its identity to the +/// grown set of people: the original people alone now get a new DM, and the +/// grown set finds this one. +/// Mutations: fork instead of growing → a different channel → RED; leave the +/// fingerprint behind → opening {A, B} finds the grown DM → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn adding_a_person_with_history_grows_the_dm_in_place() { + let state = state().await; + let tenant = community(&state, "dm-grow-in-place").await; + let (a, b, c) = (Keys::generate(), Keys::generate(), Keys::generate()); + let dm = open(&state, &tenant, &a, &[&b]).await.expect("open"); + + let (target, created) = add(&state, &tenant, &a, dm, &[&c], true) + .await + .expect("add"); + + assert_eq!((target, created), (dm, false)); + assert_eq!(members(&state, &tenant, dm).await, set_of(&[&a, &b, &c])); + assert_eq!( + open(&state, &tenant, &b, &[&a, &c]).await.expect("reopen"), + dm + ); + let fresh = open(&state, &tenant, &a, &[&b]) + .await + .expect("open original people"); + assert_ne!(fresh, dm, "the original people start a new DM"); + assert_eq!(members(&state, &tenant, fresh).await, set_of(&[&a, &b])); +} + +/// Without the history tag, adding a person starts a new DM of everyone and +/// leaves the original untouched, as before. +/// Mutation: treat a missing tag as include → the original grows → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn adding_a_person_without_history_starts_a_new_dm() { + let state = state().await; + let tenant = community(&state, "dm-grow-fork").await; + let (a, b, c) = (Keys::generate(), Keys::generate(), Keys::generate()); + let dm = open(&state, &tenant, &a, &[&b]).await.expect("open"); + + let (target, created) = add(&state, &tenant, &a, dm, &[&c], false) + .await + .expect("add"); + + assert!(created); + assert_ne!(target, dm); + assert_eq!(members(&state, &tenant, dm).await, set_of(&[&a, &b])); + assert_eq!( + members(&state, &tenant, target).await, + set_of(&[&a, &b, &c]) + ); + assert_eq!(open(&state, &tenant, &a, &[&b]).await.expect("reopen"), dm); +} + +/// When a DM of the grown people already exists, growing returns it and +/// changes nothing. +/// Mutation: drop the collision check → the unique index refuses the move, or +/// the DM grows anyway → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn growing_into_an_existing_group_returns_that_dm() { + let state = state().await; + let tenant = community(&state, "dm-grow-collision").await; + let (a, b, c) = (Keys::generate(), Keys::generate(), Keys::generate()); + let pair = open(&state, &tenant, &a, &[&b]).await.expect("open pair"); + let trio = open(&state, &tenant, &a, &[&b, &c]) + .await + .expect("open trio"); + + let (target, created) = add(&state, &tenant, &a, pair, &[&c], true) + .await + .expect("add"); + + assert_eq!((target, created), (trio, false)); + assert_eq!(members(&state, &tenant, pair).await, set_of(&[&a, &b])); + assert_eq!( + open(&state, &tenant, &a, &[&b]).await.expect("reopen"), + pair + ); +} + +/// With the history tag, an agent joins in place and never changes which DM it +/// is: the same people still find it. Without it, the agent starts a new DM of +/// everyone, as before, and this DM is untouched: an older client cannot share +/// a DM's history unseen. +/// Mutations: fork on agents with the tag → a different channel → RED; join +/// in place without it → the same channel → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn an_agent_joins_in_place_without_changing_the_dm() { + let state = state().await; + let tenant = community(&state, "dm-grow-agent").await; + let (a, b, agent) = (Keys::generate(), Keys::generate(), Keys::generate()); + make_agent(&state, &tenant, &agent, &a, "owner_only").await; + let dm = open(&state, &tenant, &a, &[&b]).await.expect("open"); + + let (forked, created) = add(&state, &tenant, &a, dm, &[&agent], false) + .await + .expect("add without history"); + assert!(created); + assert_ne!(forked, dm); + assert_eq!(members(&state, &tenant, dm).await, set_of(&[&a, &b])); + + let (target, created) = add(&state, &tenant, &a, dm, &[&agent], true) + .await + .expect("add with history"); + + assert_eq!((target, created), (dm, false)); + assert_eq!( + members(&state, &tenant, dm).await, + set_of(&[&a, &b, &agent]) + ); + assert_eq!(open(&state, &tenant, &b, &[&a]).await.expect("reopen"), dm); +} + +/// Opening a DM with people and an agent, with the history tag, finds the +/// people's DM and adds the agent to it. Without the tag it finds or makes the +/// DM of exactly those members, as before, and the people's DM is untouched. +/// Mutations: skip adding named agents to a found DM → agent missing → RED; +/// find the people's DM without the tag → the same channel → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn opening_with_an_agent_finds_the_peoples_dm_and_adds_it() { + let state = state().await; + let tenant = community(&state, "dm-open-agent").await; + let (a, b, agent) = (Keys::generate(), Keys::generate(), Keys::generate()); + make_agent(&state, &tenant, &agent, &a, "anyone").await; + let dm = open(&state, &tenant, &a, &[&b]).await.expect("open"); + + let separate = open(&state, &tenant, &a, &[&b, &agent]) + .await + .expect("open without history"); + assert_ne!(separate, dm); + assert_eq!(members(&state, &tenant, dm).await, set_of(&[&a, &b])); + assert_eq!( + open(&state, &tenant, &a, &[&b, &agent]) + .await + .expect("again without history"), + separate + ); + + assert_eq!( + open_with_history(&state, &tenant, &a, &[&b, &agent]) + .await + .expect("open with history"), + dm + ); + assert_eq!( + members(&state, &tenant, dm).await, + set_of(&[&a, &b, &agent]) + ); +} + +/// A DM of someone and their agents is still identified by all its members, +/// so each agent keeps its own DM with its owner. +/// Mutation: identify one-person DMs by people only → both agents share one +/// DM → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn each_agent_keeps_its_own_dm_with_its_owner() { + let state = state().await; + let tenant = community(&state, "dm-own-agents").await; + let (a, first, second) = (Keys::generate(), Keys::generate(), Keys::generate()); + make_agent(&state, &tenant, &first, &a, "owner_only").await; + make_agent(&state, &tenant, &second, &a, "owner_only").await; + + let dm_first = open(&state, &tenant, &a, &[&first]).await.expect("first"); + let dm_second = open(&state, &tenant, &a, &[&second]).await.expect("second"); + + assert_ne!(dm_first, dm_second); + assert_eq!( + open(&state, &tenant, &a, &[&first]).await.expect("again"), + dm_first + ); +} + +/// The nine-person limit counts people only. +/// Mutations: count agents toward the limit → the agent add is refused → RED; +/// drop the limit → a tenth person joins → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn the_limit_counts_people_not_agents() { + let state = state().await; + let tenant = community(&state, "dm-limit").await; + let a = Keys::generate(); + let others: Vec = (0..8).map(|_| Keys::generate()).collect(); + let other_refs: Vec<&Keys> = others.iter().collect(); + let agent = Keys::generate(); + make_agent(&state, &tenant, &agent, &a, "anyone").await; + let dm = open(&state, &tenant, &a, &other_refs) + .await + .expect("nine people"); + + add(&state, &tenant, &a, dm, &[&agent], true) + .await + .expect("agent beyond nine"); + let tenth = Keys::generate(); + rejected( + add(&state, &tenant, &a, dm, &[&tenth], true).await, + "at most 9 people", + ); + rejected( + add(&state, &tenant, &a, dm, &[&tenth], false).await, + "at most 9 people", + ); +} + +/// Adding someone else's agent follows its `channel_add_policy`. +/// Mutation: skip the policy check → the agent joins → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn adding_an_agent_follows_its_add_policy() { + let state = state().await; + let tenant = community(&state, "dm-agent-policy").await; + let (a, b, agent) = (Keys::generate(), Keys::generate(), Keys::generate()); + make_agent(&state, &tenant, &agent, &b, "owner_only").await; + let dm = open(&state, &tenant, &a, &[&b]).await.expect("open"); + + rejected( + add(&state, &tenant, &a, dm, &[&agent], true).await, + "policy:owner_only", + ); + rejected( + open(&state, &tenant, &a, &[&b, &agent]).await, + "policy:owner_only", + ); + assert_eq!(members(&state, &tenant, dm).await, set_of(&[&a, &b])); + + let (target, _) = add(&state, &tenant, &b, dm, &[&agent], true) + .await + .expect("owner adds"); + assert_eq!(target, dm); +} + +/// An agent naming its owner's people cannot open or join their DM: it gets +/// its own DM with them, identified by all its members. +/// Mutation: return a found DM to a non-member, or identify an agent's DM by +/// its people → the agent gets the people's DM → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn an_agent_cannot_open_its_owners_dm_with_others() { + let state = state().await; + let tenant = community(&state, "dm-agent-actor").await; + let (a, b, agent) = (Keys::generate(), Keys::generate(), Keys::generate()); + make_agent(&state, &tenant, &agent, &a, "anyone").await; + let dm = open(&state, &tenant, &a, &[&b]).await.expect("open"); + + let own = open(&state, &tenant, &agent, &[&a, &b]) + .await + .expect("agent open"); + + assert_ne!(own, dm); + assert_eq!(members(&state, &tenant, dm).await, set_of(&[&a, &b])); +} + +/// A DM an agent starts with people does not become those people's DM, and +/// they still find it when they name the agent too. +/// Mutation: identify an agent's DM by its people → B finds it without the +/// agent → RED; drop the all-members lookup → B naming the agent forks → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn an_agents_group_dm_keeps_its_own_identity() { + let state = state().await; + let tenant = community(&state, "dm-agent-group").await; + let (owner, b, c, agent) = ( + Keys::generate(), + Keys::generate(), + Keys::generate(), + Keys::generate(), + ); + make_agent(&state, &tenant, &agent, &owner, "anyone").await; + let agents_dm = open(&state, &tenant, &agent, &[&b, &c]) + .await + .expect("agent open"); + + assert_eq!( + open(&state, &tenant, &b, &[&c, &agent]) + .await + .expect("open with agent"), + agents_dm + ); + let peoples = open(&state, &tenant, &b, &[&c]).await.expect("people open"); + assert_ne!(peoples, agents_dm); +} + +/// Only people share a DM's history: an agent's add or open with the tag is +/// refused, and an add without it starts a new DM, as before. +/// Mutation: let agents grow DMs → C joins the original DM → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn an_agent_cannot_share_a_dms_history() { + let state = state().await; + let tenant = community(&state, "dm-agent-history").await; + let (a, b, c, agent) = ( + Keys::generate(), + Keys::generate(), + Keys::generate(), + Keys::generate(), + ); + make_agent(&state, &tenant, &agent, &a, "anyone").await; + let dm = open(&state, &tenant, &a, &[&b]).await.expect("open"); + add(&state, &tenant, &a, dm, &[&agent], true) + .await + .expect("add agent"); + + rejected( + add(&state, &tenant, &agent, dm, &[&c], true).await, + "only people", + ); + rejected( + open_with_history(&state, &tenant, &agent, &[&a, &b]).await, + "only people", + ); + let (target, created) = add(&state, &tenant, &agent, dm, &[&c], false) + .await + .expect("agent add"); + + assert!(created); + assert_ne!(target, dm); + assert_eq!( + members(&state, &tenant, dm).await, + set_of(&[&a, &b, &agent]) + ); +} + +/// Growing a DM never reveals another DM the actor is not in. +/// Mutation: return `Existing` without checking membership → the agent +/// learns the people's DM → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn growing_does_not_reveal_a_dm_the_actor_is_not_in() { + let state = state().await; + let tenant = community(&state, "dm-grow-reveal").await; + let (a, b, c, agent) = ( + Keys::generate(), + Keys::generate(), + Keys::generate(), + Keys::generate(), + ); + make_agent(&state, &tenant, &agent, &a, "anyone").await; + let dm = open(&state, &tenant, &a, &[&b]).await.expect("open"); + add(&state, &tenant, &a, dm, &[&agent], true) + .await + .expect("add agent"); + open(&state, &tenant, &a, &[&b, &c]).await.expect("trio"); + + let c_bytes = c.public_key().to_bytes(); + let result = state + .db + .grow_dm( + tenant.community(), + dm, + &agent.public_key().to_bytes(), + &[c_bytes.as_slice()], + &|_: &str, _: &[u8]| Ok(()), + false, + ) + .await; + + assert!( + matches!(result, Err(buzz_db::DbError::AccessDenied(_))), + "{result:?}" + ); +} + +/// The relay's moderation DM stays two-party, whether added to or opened with +/// someone else. +/// Mutation: drop either relay-key guard → a member joins → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn the_moderation_dm_cannot_grow() { + let state = state().await; + let tenant = community(&state, "dm-moderation").await; + let (a, b) = (Keys::generate(), Keys::generate()); + let relay = state.relay_keypair.public_key().to_bytes(); + let (dm, _) = state + .db + .open_dm( + tenant.community(), + &[&a.public_key().to_bytes()], + &relay, + false, + &|_: &str, _: &[u8]| Ok(()), + ) + .await + .expect("moderation dm"); + + rejected( + add(&state, &tenant, &a, dm.id, &[&b], true).await, + "cannot be changed", + ); + rejected( + add(&state, &tenant, &a, dm.id, &[&b], false).await, + "cannot be changed", + ); + let agent = Keys::generate(); + make_agent(&state, &tenant, &agent, &a, "anyone").await; + rejected( + open(&state, &tenant, &a, &[&state.relay_keypair, &agent]).await, + "cannot be changed", + ); + assert_eq!( + members(&state, &tenant, dm.id).await, + set_of(&[&a, &state.relay_keypair]) + ); +} + +/// Only `include` is a valid history value. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn an_unknown_history_value_is_refused() { + let state = state().await; + let tenant = community(&state, "dm-history-value").await; + let (a, b, c) = (Keys::generate(), Keys::generate(), Keys::generate()); + let dm = open(&state, &tenant, &a, &[&b]).await.expect("open"); + let tags = vec![ + vec!["h".into(), dm.to_string()], + vec!["p".into(), hex(&c)], + vec!["history".into(), "exclude".into()], + ]; + rejected( + submit(&state, &tenant, &a, 41011, tags).await.map(|_| ()), + "history", + ); +} + +/// A DM of just the caller and someone else's agent needs no add policy, as +/// before: anyone may message an agent. +/// Mutation: check the policy on every open → the DM is refused → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn messaging_an_agent_alone_ignores_its_add_policy() { + let state = state().await; + let tenant = community(&state, "dm-agent-alone").await; + let (a, b, agent) = (Keys::generate(), Keys::generate(), Keys::generate()); + make_agent(&state, &tenant, &agent, &b, "nobody").await; + + let dm = open(&state, &tenant, &a, &[&agent]).await.expect("open"); + assert_eq!(members(&state, &tenant, dm).await, set_of(&[&a, &agent])); +} + +/// People join a DM only through kind:41011, so a plain add, and removing +/// someone other than yourself or your own agent, are refused. +/// Mutation: drop either DM guard → the add or the removal lands → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn generic_membership_kinds_cannot_change_a_dm() { + let state = state().await; + let tenant = community(&state, "dm-generic-membership").await; + let (a, b, c) = (Keys::generate(), Keys::generate(), Keys::generate()); + let dm = open(&state, &tenant, &a, &[&b]).await.expect("open"); + let h = vec!["h".to_string(), dm.to_string()]; + + rejected( + submit( + &state, + &tenant, + &a, + 9000, + vec![h.clone(), vec!["p".into(), hex(&c)]], + ) + .await + .map(|r| (r.accepted, r.message)), + "kind:41011", + ); + rejected( + submit( + &state, + &tenant, + &a, + 9001, + vec![h, vec!["p".into(), hex(&b)]], + ) + .await + .map(|r| (r.accepted, r.message)), + "kind:41011", + ); + + assert_eq!(members(&state, &tenant, dm).await, set_of(&[&a, &b])); + assert_eq!(open(&state, &tenant, &b, &[&a]).await.expect("reopen"), dm); +} + +/// Anyone can leave a DM. The DM then stops being that group's DM, so the +/// person who left can message the group again, in a new DM. +/// Mutation: refuse kind:9022 on DMs → the leave is refused → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_person_can_leave_a_dm() { + let state = state().await; + let tenant = community(&state, "dm-leave").await; + let (a, b, c) = (Keys::generate(), Keys::generate(), Keys::generate()); + let dm = open(&state, &tenant, &a, &[&b, &c]).await.expect("open"); + + let left = submit( + &state, + &tenant, + &c, + 9022, + vec![vec!["h".into(), dm.to_string()]], + ) + .await + .expect("leave"); + assert!(left.accepted, "{}", left.message); + + assert_eq!(members(&state, &tenant, dm).await, set_of(&[&a, &b])); + let again = open(&state, &tenant, &c, &[&a, &b]) + .await + .expect("message the group again"); + assert_ne!(again, dm); +} + +/// An owner can remove their own agent from a DM, as deleting an agent does; +/// the DM stays its people's DM. Someone else's agent cannot be removed. +/// Mutation: refuse every kind:9001 for another member on DMs → the owner's +/// removal is refused → RED; allow any → B removes A's agent → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn an_owner_can_remove_their_agent_from_a_dm() { + let state = state().await; + let tenant = community(&state, "dm-remove-agent").await; + let (a, b, agent) = (Keys::generate(), Keys::generate(), Keys::generate()); + make_agent(&state, &tenant, &agent, &a, "anyone").await; + let dm = open_with_history(&state, &tenant, &a, &[&b, &agent]) + .await + .expect("open"); + let remove = vec![ + vec!["h".to_string(), dm.to_string()], + vec!["p".into(), hex(&agent)], + ]; + + rejected( + submit(&state, &tenant, &b, 9001, remove.clone()) + .await + .map(|r| (r.accepted, r.message)), + "kind:41011", + ); + let removed = submit(&state, &tenant, &a, 9001, remove) + .await + .expect("remove"); + assert!(removed.accepted, "{}", removed.message); + + assert_eq!(members(&state, &tenant, dm).await, set_of(&[&a, &b])); + assert_eq!(open(&state, &tenant, &b, &[&a]).await.expect("reopen"), dm); +} + +/// A moderation kick from a DM still removes the member, and the DM stops +/// being any group's DM: the person removed, like the rest, can message that +/// group again, in a new DM. +/// Mutation: keep the DM's identity after the kick → the removed person is +/// refused ("already exists") → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_kick_from_a_dm_releases_its_identity() { + let state = state().await; + let tenant = community(&state, "dm-kick").await; + let (a, b, c) = (Keys::generate(), Keys::generate(), Keys::generate()); + let dm = open(&state, &tenant, &a, &[&b, &c]).await.expect("open"); + + state + .db + .deploy_kick_member( + tenant.community(), + dm, + &c.public_key().to_bytes(), + &a.public_key().to_bytes(), + ) + .await + .expect("kick"); + + assert_eq!(members(&state, &tenant, dm).await, set_of(&[&a, &b])); + let again = open(&state, &tenant, &c, &[&a, &b]) + .await + .expect("message the group again"); + assert_ne!(again, dm); +} + +/// Agents are not part of a DM of people's identity, so kicking one leaves +/// the DM as that group's DM; kicking an agent from a DM of someone and +/// their agent releases it, since all its members identify it. +/// Mutation: release on every removal → the group gets a new DM → RED; +/// never release when an agent is kicked → the owner's reopen finds the +/// emptied agent DM → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn kicking_an_agent_keeps_a_group_dm_its_identity() { + let state = state().await; + let tenant = community(&state, "dm-kick-agent").await; + let (a, b, agent) = (Keys::generate(), Keys::generate(), Keys::generate()); + make_agent(&state, &tenant, &agent, &a, "anyone").await; + let group = open_with_history(&state, &tenant, &a, &[&b, &agent]) + .await + .expect("group"); + let own = open(&state, &tenant, &a, &[&agent]).await.expect("own"); + + for dm in [group, own] { + state + .db + .deploy_kick_member( + tenant.community(), + dm, + &agent.public_key().to_bytes(), + &a.public_key().to_bytes(), + ) + .await + .expect("kick"); + } + + assert_eq!( + open(&state, &tenant, &b, &[&a]).await.expect("reopen"), + group + ); + assert_ne!( + open(&state, &tenant, &a, &[&agent]) + .await + .expect("own again"), + own + ); +} + +/// Opening a DM that puts someone else's agent with anyone besides the caller +/// follows its add policy, even when no other person is in it. +/// Mutation: check policies only when people are named → the DM opens → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn opening_with_several_agents_follows_their_add_policy() { + let state = state().await; + let tenant = community(&state, "dm-agents-policy").await; + let (a, b) = (Keys::generate(), Keys::generate()); + let (theirs, mine) = (Keys::generate(), Keys::generate()); + make_agent(&state, &tenant, &theirs, &b, "nobody").await; + make_agent(&state, &tenant, &mine, &a, "owner_only").await; + + rejected( + open(&state, &tenant, &a, &[&theirs, &mine]).await, + "policy:nobody", + ); +} + +/// Adding an agent to a DM of one person and their agent moves its identity +/// to all its members: the original pair gets a new DM. +/// Mutation: keep the old identity → reopening the pair finds the grown DM → +/// RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn an_agent_joining_a_one_person_dm_moves_its_identity() { + let state = state().await; + let tenant = community(&state, "dm-one-person-grow").await; + let (a, b) = (Keys::generate(), Keys::generate()); + let (mine, theirs) = (Keys::generate(), Keys::generate()); + make_agent(&state, &tenant, &mine, &a, "anyone").await; + make_agent(&state, &tenant, &theirs, &b, "anyone").await; + let dm = open(&state, &tenant, &a, &[&mine]).await.expect("open"); + + let (target, _) = add(&state, &tenant, &a, dm, &[&theirs], true) + .await + .expect("add agent"); + assert_eq!(target, dm); + assert_eq!( + members(&state, &tenant, dm).await, + set_of(&[&a, &mine, &theirs]) + ); + assert_ne!( + open(&state, &tenant, &a, &[&mine]).await.expect("reopen"), + dm + ); + assert_eq!( + open(&state, &tenant, &a, &[&mine, &theirs]) + .await + .expect("grown"), + dm + ); +} + +/// When the grown identity is taken, an agent still joins a one-person DM in +/// place, and the DM stops answering to its old members, so reopening them +/// starts a new DM instead of one that now holds the agent. +/// Mutation: keep the old fingerprint on a lost claim → reopening A+X returns +/// the DM with Y in it → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn an_agent_joining_a_one_person_dm_whose_grown_identity_is_taken_drops_its_identity() { + let state = state().await; + let tenant = community(&state, "dm-one-person-grow-taken").await; + let (a, x, y) = (Keys::generate(), Keys::generate(), Keys::generate()); + make_agent(&state, &tenant, &x, &a, "anyone").await; + make_agent(&state, &tenant, &y, &a, "anyone").await; + let both = open(&state, &tenant, &a, &[&x, &y]) + .await + .expect("open both"); + let dm = open(&state, &tenant, &a, &[&x]).await.expect("open one"); + + let (target, created) = add(&state, &tenant, &a, dm, &[&y], true) + .await + .expect("add agent"); + + assert_eq!((target, created), (dm, false)); + assert_eq!(members(&state, &tenant, dm).await, set_of(&[&a, &x, &y])); + assert_ne!(open(&state, &tenant, &a, &[&x]).await.expect("reopen"), dm); + assert_eq!( + open(&state, &tenant, &a, &[&x, &y]) + .await + .expect("both again"), + both + ); +} + +/// A DM of one person and their agents never gains a person in place, even +/// with the history tag: adding one starts a DM of its people, and adding them +/// again opens that DM. The original keeps its members and its identity. +/// Mutation: let the tag grow it in place → the original gains B → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_person_added_to_an_agent_only_dm_starts_a_new_one() { + let state = state().await; + let tenant = community(&state, "dm-agent-only-person").await; + let (a, b, agent) = (Keys::generate(), Keys::generate(), Keys::generate()); + make_agent(&state, &tenant, &agent, &a, "anyone").await; + let dm = open(&state, &tenant, &a, &[&agent]).await.expect("open"); + + let (target, created) = add(&state, &tenant, &a, dm, &[&b], true) + .await + .expect("add person"); + + assert!(created); + assert_ne!(target, dm); + assert_eq!(members(&state, &tenant, dm).await, set_of(&[&a, &agent])); + assert_eq!(members(&state, &tenant, target).await, set_of(&[&a, &b])); + assert_eq!( + add(&state, &tenant, &a, dm, &[&b], true) + .await + .expect("add again"), + (target, false) + ); + assert_eq!( + open(&state, &tenant, &a, &[&agent]).await.expect("reopen"), + dm + ); +} + +/// An agent joining a DM still identified by all its members (from before +/// agents were told apart) moves it to its people, so they find it by name. +/// Mutation: compare against the recomputed people hash instead of the stored +/// one → the DM keeps its old fingerprint → A and B get a new DM → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn an_agent_joining_a_dm_named_by_all_its_members_moves_it_to_its_people() { + let state = state().await; + let tenant = community(&state, "dm-legacy-agent-join").await; + let (a, b, x, y) = ( + Keys::generate(), + Keys::generate(), + Keys::generate(), + Keys::generate(), + ); + make_agent(&state, &tenant, &x, &a, "anyone").await; + make_agent(&state, &tenant, &y, &a, "anyone").await; + // Without the tag, the DM is identified by all its members. + let dm = open(&state, &tenant, &a, &[&b, &x]).await.expect("open"); + + let (target, created) = add(&state, &tenant, &a, dm, &[&y], true) + .await + .expect("add agent"); + + assert_eq!((target, created), (dm, false)); + assert_eq!( + open_with_history(&state, &tenant, &b, &[&a]) + .await + .expect("people"), + dm + ); +} + +/// Reopening a DM with someone else's agent in it is not adding that agent: +/// only agents that join need their add policy. +/// Mutation: check the policy of every named agent → A's reopen is refused → +/// RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn reopening_a_dm_ignores_the_policy_of_agents_already_in_it() { + let state = state().await; + let tenant = community(&state, "dm-reopen-owner-only").await; + let (a, b, agent) = (Keys::generate(), Keys::generate(), Keys::generate()); + make_agent(&state, &tenant, &agent, &b, "owner_only").await; + let dm = open(&state, &tenant, &a, &[&b]).await.expect("open"); + add(&state, &tenant, &b, dm, &[&agent], true) + .await + .expect("owner adds"); + + assert_eq!( + open_with_history(&state, &tenant, &a, &[&b, &agent]) + .await + .expect("reopen"), + dm + ); +} + +/// An open that loses the race to create a DM still adds the agents it named: +/// the DM it tried to make is committed by another writer while its insert +/// waits, so its insert fails on the identity and it reopens that DM. +/// Mutation: report a lost race as created → the open skips adding X → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn an_open_that_loses_the_race_still_adds_its_agents() { + let state = state().await; + let tenant = community(&state, "dm-open-race").await; + let (a, b, x) = (Keys::generate(), Keys::generate(), Keys::generate()); + make_agent(&state, &tenant, &x, &a, "anyone").await; + let (a_pk, b_pk) = (a.public_key().to_bytes(), b.public_key().to_bytes()); + + // Make A and B's DM in a transaction left open, so the open's insert of + // the same identity waits on it. + let mut rival = state.db.pool().begin().await.expect("begin"); + let rival_id = Uuid::new_v4(); + sqlx::query( + "INSERT INTO channels \ + (id, community_id, name, channel_type, visibility, created_by, participant_hash) \ + VALUES ($1, $2, 'DM', 'dm', 'private', $3, $4)", + ) + .bind(rival_id) + .bind(tenant.community().as_uuid()) + .bind(a_pk.as_slice()) + .bind(buzz_db::dm::compute_participant_hash(&[a_pk.as_slice(), b_pk.as_slice()]).as_slice()) + .execute(&mut *rival) + .await + .expect("rival DM"); + for pk in [&a_pk, &b_pk] { + sqlx::query( + "INSERT INTO channel_members (community_id, channel_id, pubkey, role, invited_by) \ + VALUES ($1, $2, $3, 'member', $4)", + ) + .bind(tenant.community().as_uuid()) + .bind(rival_id) + .bind(pk.as_slice()) + .bind(a_pk.as_slice()) + .execute(&mut *rival) + .await + .expect("rival member"); + } + + let opening = tokio::spawn({ + let (state, tenant, a, b, x) = ( + state.clone(), + tenant.clone(), + a.clone(), + b.clone(), + x.clone(), + ); + async move { open_with_history(&state, &tenant, &a, &[&b, &x]).await } + }); + wait_until_blocked_by(&mut rival).await; + rival.commit().await.expect("rival commits"); + + assert_eq!(opening.await.expect("task").expect("open"), rival_id); + assert_eq!( + members(&state, &tenant, rival_id).await, + set_of(&[&a, &b, &x]) + ); +} + +/// Wait until another session is waiting on a lock `holder` holds. +async fn wait_until_blocked_by(holder: &mut sqlx::PgConnection) { + for _ in 0..200 { + let blocked: i64 = sqlx::query_scalar( + // pg_locks, unlike pg_stat_activity, is not frozen for the rest + // of the holder's transaction. + "SELECT count(*) FROM pg_locks \ + WHERE NOT granted AND pg_backend_pid() = ANY(pg_blocking_pids(pid))", + ) + .fetch_one(&mut *holder) + .await + .expect("blocked sessions"); + if blocked > 0 { + return; + } + tokio::time::sleep(std::time::Duration::from_millis(25)).await; + } + panic!("no session waited on the held lock"); +} + +/// Reopening a DM identified by all its members with the tag moves it to its +/// people, so the people alone find it afterwards. +/// Mutation: reconcile only when someone joins → A and B get a new DM → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_tagged_reopen_moves_an_old_dm_to_its_people() { + let state = state().await; + let tenant = community(&state, "dm-legacy-reopen").await; + let (a, b, x) = (Keys::generate(), Keys::generate(), Keys::generate()); + make_agent(&state, &tenant, &x, &a, "anyone").await; + let dm = open(&state, &tenant, &a, &[&b, &x]).await.expect("open"); + + assert_eq!( + open_with_history(&state, &tenant, &a, &[&b, &x]) + .await + .expect("tagged reopen"), + dm + ); + assert_eq!( + open_with_history(&state, &tenant, &b, &[&a]) + .await + .expect("people"), + dm + ); + assert_eq!(members(&state, &tenant, dm).await, set_of(&[&a, &b, &x])); +} + +/// When the people of a DM identified by all its members already have their +/// own DM, an agent added to it joins it in place, and both DMs keep their +/// identities. +/// Mutation: send the agent to the people's DM, or move the fingerprint over +/// it → the agent lands elsewhere or the write fails → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn an_agent_joins_an_old_dm_in_place_when_its_people_have_another() { + let state = state().await; + let tenant = community(&state, "dm-legacy-collision").await; + let (a, b, x, y) = ( + Keys::generate(), + Keys::generate(), + Keys::generate(), + Keys::generate(), + ); + make_agent(&state, &tenant, &x, &a, "anyone").await; + make_agent(&state, &tenant, &y, &a, "anyone").await; + let peoples = open(&state, &tenant, &a, &[&b]).await.expect("people"); + let old = open(&state, &tenant, &a, &[&b, &x]).await.expect("old"); + + assert_eq!( + add(&state, &tenant, &a, old, &[&y], true) + .await + .expect("add agent"), + (old, false) + ); + assert_eq!( + members(&state, &tenant, old).await, + set_of(&[&a, &b, &x, &y]) + ); + assert_eq!(members(&state, &tenant, peoples).await, set_of(&[&a, &b])); + assert_eq!( + open_with_history(&state, &tenant, &b, &[&a]) + .await + .expect("people"), + peoples + ); +} + +/// A new DM started from a DM carries its people, not the agents in it, so +/// no agent's add policy can block it. Agents named in the add still join. +/// Mutation: carry the source's agents → X, M and Y are in the new DMs, or the +/// policy refuses them → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_new_dm_from_a_dm_carries_only_its_people() { + let state = state().await; + let tenant = community(&state, "dm-fork-people").await; + let (a, b, c, x, m, y) = ( + Keys::generate(), + Keys::generate(), + Keys::generate(), + Keys::generate(), + Keys::generate(), + Keys::generate(), + ); + make_agent(&state, &tenant, &x, &b, "owner_only").await; + make_agent(&state, &tenant, &m, &a, "owner_only").await; + make_agent(&state, &tenant, &y, &b, "nobody").await; + + // A DM of people with someone else's agent: the new DM is its people. + let trio = open(&state, &tenant, &a, &[&b]).await.expect("open"); + add(&state, &tenant, &b, trio, &[&x], true) + .await + .expect("owner adds"); + let (forked, created) = add(&state, &tenant, &a, trio, &[&c], false) + .await + .expect("start new DM"); + assert!(created); + assert_eq!( + members(&state, &tenant, forked).await, + set_of(&[&a, &b, &c]) + ); + assert_eq!(members(&state, &tenant, trio).await, set_of(&[&a, &b, &x])); + + // These people now have a DM, but an add without the tag, as older + // clients send, puts no one into it: it starts a DM of exactly these + // members. + let (named, created) = add(&state, &tenant, &a, trio, &[&c, &m], false) + .await + .expect("start new DM with an agent"); + assert!(created); + assert_ne!(named, forked); + assert_eq!( + members(&state, &tenant, named).await, + set_of(&[&a, &b, &c, &m]) + ); + assert_eq!( + members(&state, &tenant, forked).await, + set_of(&[&a, &b, &c]) + ); + assert_eq!(members(&state, &tenant, trio).await, set_of(&[&a, &b, &x])); + + // With the tag, the add lands in the DM these people already have, and + // the agent joins it, with its history. + let (named, created) = add(&state, &tenant, &a, trio, &[&c, &m], true) + .await + .expect("join their DM with an agent"); + assert_eq!((named, created), (forked, false)); + assert_eq!( + members(&state, &tenant, forked).await, + set_of(&[&a, &b, &c, &m]) + ); + + // A DM of one person and agents, theirs or not: the new DM is people + // only, and the next one opens it. + let mut pair = None; + for (agent, history) in [(&m, true), (&y, false)] { + let solo = open(&state, &tenant, &a, &[agent]).await.expect("solo"); + let (target, created) = add(&state, &tenant, &a, solo, &[&c], history) + .await + .expect("add a person"); + assert_ne!(target, solo); + assert_eq!(created, pair.is_none()); + assert_eq!(*pair.get_or_insert(target), target); + assert_eq!(members(&state, &tenant, target).await, set_of(&[&a, &c])); + } + let pair = pair.expect("a DM of A and C"); + + // From a DM of one person, an agent named with a person: without the + // tag, a DM of exactly these members; with it, the DM those people + // already have, which the agent joins with its history. + let solo = open(&state, &tenant, &a, &[&y]).await.expect("solo"); + let (untagged, created) = add(&state, &tenant, &a, solo, &[&c, &m], false) + .await + .expect("add a person and an agent"); + assert!(created); + assert_ne!(untagged, pair); + assert_eq!( + members(&state, &tenant, untagged).await, + set_of(&[&a, &c, &m]) + ); + assert_eq!(members(&state, &tenant, pair).await, set_of(&[&a, &c])); + assert_eq!( + add(&state, &tenant, &a, solo, &[&c, &m], true) + .await + .expect("add a person and an agent, with history"), + (pair, false) + ); + assert_eq!(members(&state, &tenant, pair).await, set_of(&[&a, &c, &m])); + assert_eq!(members(&state, &tenant, solo).await, set_of(&[&a, &y])); +} + +/// A client from before agents were told apart opens a DM by all its +/// members. A DM whose agents joined it in place holds exactly those members, +/// so the open lands there instead of making another; a DM that holds others +/// too is not theirs. +/// Mutation: drop the people's-DM fallback from untagged opens → a second DM +/// of A, B and X is made → RED; skip its members check → the open of A, B and +/// Y lands in a DM that also holds X → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn an_untagged_open_finds_the_dm_agents_joined_in_place() { + let state = state().await; + let tenant = community(&state, "dm-untagged-grown").await; + let (a, b, x, y) = ( + Keys::generate(), + Keys::generate(), + Keys::generate(), + Keys::generate(), + ); + make_agent(&state, &tenant, &x, &a, "owner_only").await; + make_agent(&state, &tenant, &y, &a, "owner_only").await; + let dm = open(&state, &tenant, &a, &[&b]).await.expect("open"); + add(&state, &tenant, &a, dm, &[&x], true) + .await + .expect("agent joins"); + + for (actor, others) in [(&a, [&b, &x]), (&b, [&a, &x])] { + assert_eq!( + open(&state, &tenant, actor, &others).await.expect("reopen"), + dm + ); + } + assert_eq!(members(&state, &tenant, dm).await, set_of(&[&a, &b, &x])); + + // Without X, or with another agent, it is not the DM asked for. + let other = open(&state, &tenant, &a, &[&b, &y]).await.expect("open"); + assert_ne!(other, dm); + assert_eq!(members(&state, &tenant, other).await, set_of(&[&a, &b, &y])); +} + +/// There is one DM per group of people, and agents joining it don't fork it. +/// An open without the tag that names only the people, as an older client +/// sends, opens their DM with the agents in it, whether an agent joined it +/// in place or one of two agents left a DM first made with all of them. +/// Mutation: require exact membership on the first lookup and refuse the +/// people's DM on an insert conflict, giving A and B a separate DM → the +/// open fails → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn an_untagged_open_of_the_people_finds_their_dm_with_its_agents() { + let state = state().await; + let tenant = community(&state, "dm-untagged-people").await; + let (a, b, c, x, y) = ( + Keys::generate(), + Keys::generate(), + Keys::generate(), + Keys::generate(), + Keys::generate(), + ); + make_agent(&state, &tenant, &x, &a, "anyone").await; + make_agent(&state, &tenant, &y, &a, "anyone").await; + + // An agent joins a DM of A and B in place. + let dm = open(&state, &tenant, &a, &[&b]).await.expect("open"); + add(&state, &tenant, &a, dm, &[&x], true) + .await + .expect("agent joins"); + assert_eq!(open(&state, &tenant, &b, &[&a]).await.expect("reopen"), dm); + assert_eq!(members(&state, &tenant, dm).await, set_of(&[&a, &b, &x])); + + // A DM first made with two agents, one of whom then leaves. + let group = open(&state, &tenant, &a, &[&c, &x, &y]) + .await + .expect("open with agents"); + let removed = submit( + &state, + &tenant, + &a, + 9001, + vec![ + vec!["h".to_string(), group.to_string()], + vec!["p".into(), hex(&x)], + ], + ) + .await + .expect("remove"); + assert!(removed.accepted, "{}", removed.message); + assert_eq!( + open(&state, &tenant, &c, &[&a]).await.expect("reopen"), + group + ); + assert_eq!(members(&state, &tenant, group).await, set_of(&[&a, &c, &y])); +} + +/// An agent already in a DM and named in an add joins whichever DM the add +/// lands in: a new DM, the DM its people already have, or the new DM a DM of +/// one person starts. It still needs its add policy in a new DM, and the DM +/// the add came from keeps its members. +/// Mutation: leave out additions already in the source → X is missing from +/// each target → RED; exempt them from the policy → Y joins → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_named_agent_from_the_dm_joins_the_dm_the_add_lands_in() { + let state = state().await; + let tenant = community(&state, "dm-named-source-agent").await; + let (a, b, c, d, e, x, y) = ( + Keys::generate(), + Keys::generate(), + Keys::generate(), + Keys::generate(), + Keys::generate(), + Keys::generate(), + Keys::generate(), + ); + make_agent(&state, &tenant, &x, &b, "anyone").await; + make_agent(&state, &tenant, &y, &b, "owner_only").await; + let source = open(&state, &tenant, &a, &[&b]).await.expect("open"); + add(&state, &tenant, &b, source, &[&x, &y], true) + .await + .expect("owner adds"); + let source_members = set_of(&[&a, &b, &x, &y]); + + // Start a new DM. + let (forked, created) = add(&state, &tenant, &a, source, &[&c, &x], false) + .await + .expect("start new DM"); + assert!(created); + assert_eq!( + members(&state, &tenant, forked).await, + set_of(&[&a, &b, &c, &x]) + ); + + // Include history, landing in the DM these people already have. + let existing = open(&state, &tenant, &a, &[&b, &d]).await.expect("abd"); + assert_eq!( + add(&state, &tenant, &a, source, &[&d, &x], true) + .await + .expect("include history"), + (existing, false) + ); + assert_eq!( + members(&state, &tenant, existing).await, + set_of(&[&a, &b, &d, &x]) + ); + + // Someone else's owner_only agent named for a new DM is still refused. + rejected( + add(&state, &tenant, &a, source, &[&e, &y], false).await, + "policy:owner_only", + ); + assert_eq!(members(&state, &tenant, source).await, source_members); + + // A DM of one person starts a new DM, which the named agent joins. + let solo = open(&state, &tenant, &a, &[&x]).await.expect("solo"); + let (target, created) = add(&state, &tenant, &a, solo, &[&c, &x], true) + .await + .expect("add a person"); + assert!(created); + assert_eq!( + members(&state, &tenant, target).await, + set_of(&[&a, &c, &x]) + ); + assert_eq!(members(&state, &tenant, solo).await, set_of(&[&a, &x])); +} + +/// A new DM started from a DM holds who is in that DM when it is made, not +/// who was in it when the add arrived. +/// Mutation: build the new DM from members read before taking the DM's lock +/// → C, who left meanwhile, is in it → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_new_dm_from_a_dm_holds_its_current_members() { + let state = state().await; + let tenant = community(&state, "dm-fork-live").await; + let (a, b, c, d) = ( + Keys::generate(), + Keys::generate(), + Keys::generate(), + Keys::generate(), + ); + let dm = open(&state, &tenant, &a, &[&b, &c]).await.expect("open"); + + // Hold the DM's membership lock until the add waits on it, then let C + // leave and release it. If the add did not take this lock, it would never + // wait, and the test fails rather than passing. + let mut lock = state.db.pool().begin().await.expect("begin"); + sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))") + .bind(format!( + "buzz_channel_membership:{}:{dm}", + tenant.community().as_uuid() + )) + .execute(&mut *lock) + .await + .expect("lock"); + let adding = tokio::spawn({ + let (state, tenant, a, d) = (state.clone(), tenant.clone(), a.clone(), d.clone()); + async move { add(&state, &tenant, &a, dm, &[&d], false).await } + }); + wait_until_blocked_by(&mut lock).await; + sqlx::query( + "UPDATE channel_members SET removed_at = NOW() \ + WHERE channel_id = $1 AND pubkey = $2", + ) + .bind(dm) + .bind(c.public_key().to_bytes().as_slice()) + .execute(&mut *lock) + .await + .expect("C leaves"); + lock.commit().await.expect("release"); + + let (target, created) = adding.await.expect("task").expect("add"); + assert!(created); + assert_eq!( + members(&state, &tenant, target).await, + set_of(&[&a, &b, &d]) + ); +} + +/// The relay joins no DM but its moderation DM. +/// Mutation: drop the relay-key check on additions → the relay joins → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn the_relay_cannot_be_added_to_a_dm() { + let state = state().await; + let tenant = community(&state, "dm-add-relay").await; + let (a, b) = (Keys::generate(), Keys::generate()); + let dm = open(&state, &tenant, &a, &[&b]).await.expect("open"); + + for history in [true, false] { + rejected( + add(&state, &tenant, &a, dm, &[&state.relay_keypair], history).await, + "cannot be changed", + ); + } + assert_eq!(members(&state, &tenant, dm).await, set_of(&[&a, &b])); +} + +/// The limit counts the caller only if they are a person: an agent may open a +/// DM with nine people, and no more. +/// Mutation: count the caller as a person → the agent's DM is refused → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn an_agent_can_open_a_dm_with_nine_people() { + let state = state().await; + let tenant = community(&state, "dm-agent-nine").await; + let (owner, agent) = (Keys::generate(), Keys::generate()); + make_agent(&state, &tenant, &agent, &owner, "anyone").await; + let people: Vec = (0..9).map(|_| Keys::generate()).collect(); + let nine: Vec<&Keys> = people.iter().collect(); + + let dm = open(&state, &tenant, &agent, &nine) + .await + .expect("nine people"); + let mut everyone = nine.clone(); + everyone.push(&agent); + assert_eq!(members(&state, &tenant, dm).await, set_of(&everyone)); + + let mut ten = nine; + ten.push(&owner); + rejected( + open(&state, &tenant, &agent, &ten).await, + "at most 9 people", + ); +} + +/// Removing an agent from a DM identified by all its members (from before +/// agents were told apart) leaves it its people's DM, whether its owner removes +/// it or it leaves, unless they already have another DM. +/// Mutation: give the identity up on every removal → B gets a new DM → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn removing_an_agent_moves_an_old_dm_to_its_people() { + let state = state().await; + let tenant = community(&state, "dm-legacy-remove-agent").await; + let (a, b, c, d, x) = ( + Keys::generate(), + Keys::generate(), + Keys::generate(), + Keys::generate(), + Keys::generate(), + ); + make_agent(&state, &tenant, &x, &a, "anyone").await; + let removed = open(&state, &tenant, &a, &[&b, &x]).await.expect("open"); + let left = open(&state, &tenant, &a, &[&c, &x]).await.expect("open"); + let peoples = open(&state, &tenant, &a, &[&d]).await.expect("people"); + let shadowed = open(&state, &tenant, &a, &[&d, &x]).await.expect("open"); + + let remove = |dm: Uuid| { + vec![ + vec!["h".to_string(), dm.to_string()], + vec!["p".into(), hex(&x)], + ] + }; + for dm in [removed, shadowed] { + let result = submit(&state, &tenant, &a, 9001, remove(dm)) + .await + .expect("remove"); + assert!(result.accepted, "{}", result.message); + } + let result = submit( + &state, + &tenant, + &x, + 9022, + vec![vec!["h".into(), left.to_string()]], + ) + .await + .expect("leave"); + assert!(result.accepted, "{}", result.message); + + for (person, dm) in [(&b, removed), (&c, left), (&d, peoples)] { + assert_eq!( + open_with_history(&state, &tenant, person, &[&a]) + .await + .expect("reopen"), + dm + ); + } + assert_ne!( + open(&state, &tenant, &a, &[&d, &x]).await.expect("reopen"), + shadowed, + "a DM that could not take its people's identity gives its own up" + ); +} + +/// A tagged add that lands in the DM its people already have checks agents +/// against that DM: one already in it needs no permission. +/// Mutation: check policies before finding the other DM → the add is refused +/// → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn agents_are_checked_against_the_dm_they_join() { + let state = state().await; + let tenant = community(&state, "dm-existing-policy").await; + let (a, b, c, x) = ( + Keys::generate(), + Keys::generate(), + Keys::generate(), + Keys::generate(), + ); + make_agent(&state, &tenant, &x, &b, "owner_only").await; + let trio = open(&state, &tenant, &a, &[&b, &c]).await.expect("trio"); + add(&state, &tenant, &b, trio, &[&x], true) + .await + .expect("owner adds"); + let pair = open(&state, &tenant, &a, &[&b]).await.expect("pair"); + + assert_eq!( + add(&state, &tenant, &a, pair, &[&c, &x], true) + .await + .expect("add"), + (trio, false) + ); + assert_eq!(members(&state, &tenant, pair).await, set_of(&[&a, &b])); +} + +/// A DM someone left keeps their history, so an agent joining it, even as the +/// only other member, needs its add policy. +/// Mutation: exempt any DM of the actor and one agent → the agent joins → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn an_agent_needs_its_policy_to_join_a_dm_someone_left() { + let state = state().await; + let tenant = community(&state, "dm-left-policy").await; + let (a, b, x) = (Keys::generate(), Keys::generate(), Keys::generate()); + make_agent(&state, &tenant, &x, &b, "owner_only").await; + let dm = open(&state, &tenant, &a, &[&b]).await.expect("open"); + let result = submit( + &state, + &tenant, + &b, + 9022, + vec![vec!["h".into(), dm.to_string()]], + ) + .await + .expect("leave"); + assert!(result.accepted, "{}", result.message); + + rejected( + add(&state, &tenant, &a, dm, &[&x], true).await, + "policy:owner_only", + ); + assert_eq!(members(&state, &tenant, dm).await, set_of(&[&a])); +} + +/// A new DM starts only from a live, unarchived DM, checked under its lock. +/// Mutation: skip the check when starting a new DM → the archived DM forks → +/// RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn a_new_dm_cannot_start_from_an_archived_dm() { + let state = state().await; + let tenant = community(&state, "dm-fork-archived").await; + let (a, b, c) = (Keys::generate(), Keys::generate(), Keys::generate()); + let dm = open(&state, &tenant, &a, &[&b]).await.expect("open"); + sqlx::query("UPDATE channels SET archived_at = NOW() WHERE id = $1") + .bind(dm) + .execute(state.db.pool()) + .await + .expect("archive"); + + let c_pk = c.public_key().to_bytes(); + let result = state + .db + .fork_dm( + tenant.community(), + dm, + &a.public_key().to_bytes(), + &[c_pk.as_slice()], + true, + &|_: &str, _: &[u8]| Ok(()), + ) + .await; + assert!( + matches!(&result, Err(buzz_db::DbError::AccessDenied(m)) if m.contains("archived")), + "{result:?}" + ); +} + +/// Adds `others` to `dm` tagged `["history", "ask"]`. +async fn ask( + state: &Arc, + tenant: &TenantContext, + actor: &Keys, + dm: Uuid, + others: &[&Keys], +) -> Result<(Uuid, bool), IngestError> { + let mut tags: Vec> = vec![vec!["h".into(), dm.to_string()]]; + tags.extend(others.iter().map(|k| vec!["p".into(), hex(k)])); + tags.push(vec!["history".into(), "ask".into()]); + submit(state, tenant, actor, 41011, tags) + .await + .map(|r| response_channel(&r)) +} + +/// Asking first, agents alone join in place with the DM's history, as with +/// `include`. +/// Mutation: refuse every ask → the agent is not added → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn asking_adds_agents_alone_in_place() { + let state = state().await; + let tenant = community(&state, "dm-ask-agents").await; + let (a, b, agent) = (Keys::generate(), Keys::generate(), Keys::generate()); + make_agent(&state, &tenant, &agent, &a, "anyone").await; + let dm = open(&state, &tenant, &a, &[&b]).await.expect("open"); + + let (target, created) = ask(&state, &tenant, &a, dm, &[&agent]).await.expect("ask"); + + assert_eq!((target, created), (dm, false)); + assert_eq!( + members(&state, &tenant, dm).await, + set_of(&[&a, &b, &agent]) + ); +} + +/// Asking first, a person joining a DM of two or more people is refused with +/// the exact reason, nothing changes, and the refused command is not +/// remembered, so the same event is refused again rather than taken as done. +/// Agents named with the person do not join either. Mutations: grow as with +/// `include` → the person joins → RED; commit the command before refusing → +/// the second send is a duplicate → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn asking_refuses_people_joining_a_dm_of_two_people() { + let state = state().await; + let tenant = community(&state, "dm-ask-people").await; + let (a, b, c, agent) = ( + Keys::generate(), + Keys::generate(), + Keys::generate(), + Keys::generate(), + ); + make_agent(&state, &tenant, &agent, &a, "anyone").await; + let dm = open(&state, &tenant, &a, &[&b]).await.expect("open"); + + let event = EventBuilder::new(Kind::Custom(41011), "") + .tags( + [ + vec!["h".to_string(), dm.to_string()], + vec!["p".into(), hex(&c)], + vec!["p".into(), hex(&agent)], + vec!["history".into(), "ask".into()], + ] + .into_iter() + .map(|tag| Tag::parse(tag).expect("tag")), + ) + .sign_with_keys(&a) + .expect("sign"); + for _ in 0..2 { + match ingest_event(&state, &tenant, event.clone(), http_auth(&a)).await { + Err(IngestError::Rejected(message)) => assert_eq!(message, "needs-choice: history"), + Err(other) => panic!("expected the history choice, got {other:?}"), + Ok(result) => panic!("expected the history choice, got {:?}", result.message), + } + } + + assert_eq!(members(&state, &tenant, dm).await, set_of(&[&a, &b])); + assert_eq!(open(&state, &tenant, &a, &[&b]).await.expect("reopen"), dm); + let (target, created) = add(&state, &tenant, &a, dm, &[&c, &agent], true) + .await + .expect("add with history"); + assert_eq!((target, created), (dm, false)); + assert_eq!( + members(&state, &tenant, dm).await, + set_of(&[&a, &b, &c, &agent]) + ); +} + +/// Asking first, a person added to a DM of one person and their agents starts +/// a new DM without a choice, as with `include`, and the DM stays theirs. +/// Mutation: check for a choice before the one-person rule → refused → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn asking_starts_a_new_dm_for_a_person_added_to_a_dm_of_one_person() { + let state = state().await; + let tenant = community(&state, "dm-ask-one-person").await; + let (a, c, agent) = (Keys::generate(), Keys::generate(), Keys::generate()); + make_agent(&state, &tenant, &agent, &a, "anyone").await; + let dm = open(&state, &tenant, &a, &[&agent]).await.expect("open"); + + let (target, created) = ask(&state, &tenant, &a, dm, &[&c]).await.expect("ask"); + + assert!(created); + assert_ne!(target, dm); + assert_eq!(members(&state, &tenant, dm).await, set_of(&[&a, &agent])); + assert_eq!(members(&state, &tenant, target).await, set_of(&[&a, &c])); +} + +/// An agent cannot ask either, and only adds take `ask`. +/// Mutations: let agents ask → the agent's add is answered → RED; accept +/// `ask` on kind:41010 → the open succeeds → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn only_people_ask_and_only_when_adding() { + let state = state().await; + let tenant = community(&state, "dm-ask-who").await; + let (a, b, c, agent) = ( + Keys::generate(), + Keys::generate(), + Keys::generate(), + Keys::generate(), + ); + make_agent(&state, &tenant, &agent, &a, "anyone").await; + let dm = open(&state, &tenant, &a, &[&b]).await.expect("open"); + add(&state, &tenant, &a, dm, &[&agent], true) + .await + .expect("add agent"); + + rejected(ask(&state, &tenant, &agent, dm, &[&c]).await, "only people"); + let tags = vec![ + vec!["p".into(), hex(&b)], + vec!["history".into(), "ask".into()], + ]; + rejected( + submit(&state, &tenant, &a, 41010, tags).await.map(|_| ()), + "history", + ); +} diff --git a/crates/buzz-relay/src/handlers/group_state_postgres_tests.rs b/crates/buzz-relay/src/handlers/group_state_postgres_tests.rs index 010240aeb4..c6955c3a4d 100644 --- a/crates/buzz-relay/src/handlers/group_state_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/group_state_postgres_tests.rs @@ -1620,6 +1620,8 @@ async fn a_relay_operator_may_not_rename_an_unlisted_channel() { &other.public_key().to_bytes(), ], &owner.public_key().to_bytes(), + false, + &|_: &str, _: &[u8]| Ok(()), ) .await .expect("open dm"); diff --git a/crates/buzz-relay/src/handlers/mod.rs b/crates/buzz-relay/src/handlers/mod.rs index d1384b9ff3..fa62b337e5 100644 --- a/crates/buzz-relay/src/handlers/mod.rs +++ b/crates/buzz-relay/src/handlers/mod.rs @@ -23,6 +23,8 @@ mod create_with_members_postgres_tests; #[cfg(test)] mod deletion_postgres_tests; #[cfg(test)] +mod dm_growth_postgres_tests; +#[cfg(test)] mod edit_metadata_postgres_tests; /// EVENT handler — WS dispatcher → ingest pipeline → fan-out. pub mod event; diff --git a/crates/buzz-relay/src/handlers/moderation_notices.rs b/crates/buzz-relay/src/handlers/moderation_notices.rs index d5d6bc2c5c..b7a66546e5 100644 --- a/crates/buzz-relay/src/handlers/moderation_notices.rs +++ b/crates/buzz-relay/src/handlers/moderation_notices.rs @@ -115,6 +115,9 @@ pub async fn send_moderation_notice( tenant.community(), &[recipient_pubkey], relay_pubkey_bytes.as_slice(), + false, + // Two-party: no agent needs permission. + &|_: &str, _: &[u8]| Ok(()), ) .await?; let dm_channel_id = dm_channel.id; diff --git a/crates/buzz-relay/src/handlers/side_effects.rs b/crates/buzz-relay/src/handlers/side_effects.rs index cc0c10ca3c..b389e10191 100644 --- a/crates/buzz-relay/src/handlers/side_effects.rs +++ b/crates/buzz-relay/src/handlers/side_effects.rs @@ -629,6 +629,10 @@ async fn actor_owns_any_owner_agent( Ok(false) } +/// Why kind:9000, and kind:9001 for anyone but yourself or your own agent, +/// are refused on a DM. +const DM_MEMBERSHIP_REFUSAL: &str = "DM members change only through kind:41011"; + /// Validate an admin kind event BEFORE storage. pub async fn validate_admin_event( tenant: &TenantContext, @@ -683,6 +687,21 @@ pub async fn validate_admin_event( if kind != 9002 && channel.archived_at.is_some() && !is_self_departure(event) { return Err(anyhow::anyhow!("channel is archived")); } + // A DM is identified by its people, so people join it only through + // kind:41011, which keeps that identity in step. Anyone may leave, and + // an owner may remove their own agent: every removal releases the DM's + // identity when its people change (`release_dm_identity`). + if channel.channel_type == "dm" && kind == 9001 { + let target = extract_p_tag(event).ok_or_else(|| anyhow::anyhow!("missing p tag"))?; + if target != actor_bytes + && !state + .db + .is_agent_owner(tenant.community(), &target, &actor_bytes) + .await? + { + return Err(anyhow::anyhow!(DM_MEMBERSHIP_REFUSAL)); + } + } match kind { // Ingest validates kind:9000 with `validate_put_user`, which keeps @@ -1938,6 +1957,9 @@ pub(crate) async fn validate_put_user( if channel.archived_at.is_some() { anyhow::bail!("channel is archived"); } + if channel.channel_type == "dm" { + anyhow::bail!(DM_MEMBERSHIP_REFUSAL); + } let targets = put_user_targets(event)?; let actor_bytes = event.pubkey.to_bytes().to_vec(); diff --git a/crates/buzz-sdk/src/builders.rs b/crates/buzz-sdk/src/builders.rs index 6c5a306562..8a83c86f41 100644 --- a/crates/buzz-sdk/src/builders.rs +++ b/crates/buzz-sdk/src/builders.rs @@ -1981,11 +1981,35 @@ pub fn build_workflow_approval( /// Build a DM open event (kind 41010). /// -/// `pubkeys` must be 1–8 hex-encoded pubkeys to include in the DM conversation. +/// `pubkeys` are the hex-encoded pubkeys of everyone else in the DM, at least +/// one. The relay finds the DM of exactly these members or, when they are all +/// people, their DM, which agents may have joined (there is one DM per group +/// of people). Otherwise it makes a DM of exactly these members. It refuses +/// a DM of more than nine people, the caller included; agents do not count. +/// To find the DM of the named people whichever agents are named, and add +/// the named agents to it, use [`build_dm_open_with_history`]. +/// +/// The relay answers kind 41010 and kind 41011 with +/// `response:{"channel_id":"","created":}`, where `created` is +/// true only when a new DM was made. pub fn build_dm_open(pubkeys: &[&str]) -> Result { - if pubkeys.is_empty() || pubkeys.len() > 8 { + dm_open(pubkeys, false) +} + +/// Build a DM open event (kind 41010) with a `["history", "include"]` tag. +/// +/// The relay finds the DM of the named people, whatever agents it holds, adds +/// any named agents it lacks, so they see its history, and makes the DM if +/// there is none. `pubkeys` is as for [`build_dm_open`]. Only people may send +/// the tag: the relay refuses it from an agent. +pub fn build_dm_open_with_history(pubkeys: &[&str]) -> Result { + dm_open(pubkeys, true) +} + +fn dm_open(pubkeys: &[&str], include_history: bool) -> Result { + if pubkeys.is_empty() { return Err(SdkError::InvalidInput( - "dm open requires 1-8 pubkeys".into(), + "dm open requires at least 1 pubkey".into(), )); } let mut tags = Vec::with_capacity(pubkeys.len()); @@ -1993,13 +2017,37 @@ pub fn build_dm_open(pubkeys: &[&str]) -> Result { let validated = check_pubkey_hex(pk, "pubkey")?; tags.push(tag(&["p", &validated])?); } + if include_history { + tags.push(tag(&["history", "include"])?); + } Ok(EventBuilder::new(Kind::Custom(KIND_DM_OPEN as u16), "").tags(tags)) } /// Build a DM add-member event (kind 41011). -pub fn build_dm_add_member(channel_id: Uuid, pubkey: &str) -> Result { +/// +/// With `include_history`, the member joins this DM and sees its history, +/// unless a person is joining a DM of at most one person and their agents. +/// Otherwise it finds or makes a DM of this DM's people and the member, as +/// [`build_dm_open`] does; agents already here stay behind. Only people may send the history +/// tag: the relay refuses it from an agent. +/// +/// The relay also accepts `["history", "ask"]` on kind 41011, which this +/// builder does not send: agents, and people added to a DM of at most one +/// person, are added as with `include`, while people who would join a DM of +/// two or more people are refused with the exact message +/// `needs-choice: history` and nothing changes. The client then asks whether +/// they should see the DM's history and sends the add again, tagged `include` +/// or untagged. +pub fn build_dm_add_member( + channel_id: Uuid, + pubkey: &str, + include_history: bool, +) -> Result { let pk = check_pubkey_hex(pubkey, "pubkey")?; - let tags = vec![tag(&["h", &channel_id.to_string()])?, tag(&["p", &pk])?]; + let mut tags = vec![tag(&["h", &channel_id.to_string()])?, tag(&["p", &pk])?]; + if include_history { + tags.push(tag(&["history", "include"])?); + } Ok(EventBuilder::new(Kind::Custom(KIND_DM_ADD_MEMBER as u16), "").tags(tags)) } @@ -5102,6 +5150,25 @@ mod tests { let ev = sign(build_dm_open(&[&pk]).unwrap()); assert_eq!(ev.kind.as_u16(), 41010); assert!(has_tag(&ev, "p", &pk)); + assert!(!ev.tags.iter().any(|t| t.as_slice()[0] == "history")); + } + + #[test] + fn dm_open_with_history_tags_the_open() { + let (a, b) = ("a".repeat(64), "b".repeat(64)); + let ev = sign(build_dm_open_with_history(&[&a, &b]).unwrap()); + assert_eq!(ev.kind.as_u16(), 41010); + assert!(has_tag(&ev, "p", &a)); + assert!(has_tag(&ev, "p", &b)); + assert!(has_tag(&ev, "history", "include")); + } + + #[test] + fn dm_open_with_history_validates_like_dm_open() { + for pubkeys in [&[][..], &["bad-hex"][..]] { + let err = build_dm_open_with_history(pubkeys).unwrap_err(); + assert!(matches!(err, SdkError::InvalidInput(_))); + } } #[test] @@ -5111,11 +5178,16 @@ mod tests { } #[test] - fn dm_open_rejects_over_8_pubkeys() { + fn dm_open_leaves_the_people_limit_to_the_relay() { + // Agents do not count toward the relay's nine-person limit, and an + // agent caller is not one of the nine, so the SDK caps nothing. let pk = "a".repeat(64); - let pks: Vec<&str> = vec![pk.as_str(); 9]; - let err = build_dm_open(&pks).unwrap_err(); - assert!(matches!(err, SdkError::InvalidInput(_))); + let pks: Vec<&str> = vec![pk.as_str(); 12]; + let ev = sign(build_dm_open(&pks).unwrap()); + assert_eq!( + ev.tags.iter().filter(|t| t.as_slice()[0] == "p").count(), + 12 + ); } #[test] @@ -5128,15 +5200,22 @@ mod tests { fn dm_add_member_happy_path() { let cid = uuid(); let pk = "b".repeat(64); - let ev = sign(build_dm_add_member(cid, &pk).unwrap()); + let ev = sign(build_dm_add_member(cid, &pk, false).unwrap()); assert_eq!(ev.kind.as_u16(), 41011); assert!(has_tag(&ev, "h", &cid.to_string())); assert!(has_tag(&ev, "p", &pk)); + assert!(!ev.tags.iter().any(|t| t.as_slice()[0] == "history")); + } + + #[test] + fn dm_add_member_with_history() { + let ev = sign(build_dm_add_member(uuid(), &"b".repeat(64), true).unwrap()); + assert!(has_tag(&ev, "history", "include")); } #[test] fn dm_add_member_rejects_bad_pubkey() { - let err = build_dm_add_member(uuid(), "short").unwrap_err(); + let err = build_dm_add_member(uuid(), "short", false).unwrap_err(); assert!(matches!(err, SdkError::InvalidInput(_))); }