diff --git a/crates/buzz-db/src/store/user_deletion/account_batches/ownership.rs b/crates/buzz-db/src/store/user_deletion/account_batches/ownership.rs index df84e2ed435..2bfc94edbcd 100644 --- a/crates/buzz-db/src/store/user_deletion/account_batches/ownership.rs +++ b/crates/buzz-db/src/store/user_deletion/account_batches/ownership.rs @@ -1,8 +1,6 @@ //! Direct ownership is rediscovered per handler and checked in each batch. use super::*; -const MAX_AGENTS: i64 = 10_000; - impl UserDeletionStore { /// Fetch the target's current directly owned agents in this community, then /// print or apply bounded account batches. Retries repeat discovery. @@ -76,21 +74,18 @@ pub(super) async fn agents( target: &str, lock: bool, ) -> Result> { - let sql = if lock { - "SELECT encode(pubkey,'hex') FROM users WHERE community_id=$1 AND agent_owner_pubkey=decode($2,'hex') AND pubkey<>decode($2,'hex') ORDER BY pubkey LIMIT $3 FOR SHARE" - } else { - "SELECT encode(pubkey,'hex') FROM users WHERE community_id=$1 AND agent_owner_pubkey=decode($2,'hex') AND pubkey<>decode($2,'hex') ORDER BY pubkey LIMIT $3" - }; - let keys: Vec = sqlx::query_scalar(sql) - .bind(community) - .bind(target) - .bind(MAX_AGENTS + 1) - .fetch_all(conn) - .await?; - if keys.len() > MAX_AGENTS as usize { - return Err(invalid("account handler exceeds agent limit")); - } - Ok(keys) + Ok(super::super::agent_ownership::discover( + conn, + target, + Some(community), + lock, + super::super::agent_ownership::DiscoveryLimit::AgentRows, + ) + .await? + .agents + .into_iter() + .map(|(_, key)| key) + .collect()) } pub(super) async fn recheck(conn: &mut PgConnection, options: &Options, lock: bool) -> Result<()> { diff --git a/crates/buzz-db/src/store/user_deletion/account_batches/scope.rs b/crates/buzz-db/src/store/user_deletion/account_batches/scope.rs index bf4fc2fbb54..bf9e3195b9c 100644 --- a/crates/buzz-db/src/store/user_deletion/account_batches/scope.rs +++ b/crates/buzz-db/src/store/user_deletion/account_batches/scope.rs @@ -3,7 +3,7 @@ use super::*; use serde::Deserialize; use std::collections::BTreeSet; -const MAX_TARGETS: usize = 10_000; +use super::super::agent_ownership::{self, MAX_TARGETS}; /// Saved account cleanup inputs. Agent keys are a discovery snapshot only; /// each handler fetches current ownership. Keep ownership rows until cleanup ends. @@ -87,12 +87,15 @@ impl UserDeletionStore { if communities.len() > super::super::MAX_COMMUNITIES { return Err(invalid("account scope exceeds community limit")); } - let agents: Vec<(Uuid, String)> = sqlx::query_as( - "SELECT community_id,encode(pubkey,'hex') FROM users WHERE agent_owner_pubkey=decode($1,'hex') AND pubkey<>decode($1,'hex') ORDER BY community_id,pubkey LIMIT $2") - .bind(&target).bind((MAX_TARGETS + 1) as i64).fetch_all(&mut *tx).await?; - if agents.len() > MAX_TARGETS { - return Err(invalid("account scope exceeds target limit")); - } + let agents = agent_ownership::discover( + &mut tx, + &target, + None, + false, + agent_ownership::DiscoveryLimit::AgentRows, + ) + .await? + .agents; let scope = AccountScope { version: 1, target: target.clone(), diff --git a/crates/buzz-db/src/store/user_deletion/agent_ownership.rs b/crates/buzz-db/src/store/user_deletion/agent_ownership.rs new file mode 100644 index 00000000000..d85a3b3812f --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/agent_ownership.rs @@ -0,0 +1,100 @@ +//! One ownership rule for every user-deletion handler, independent of membership. +use super::normalize_user_deletion_pubkey; +use crate::{DbError, Result}; +use sqlx::{PgConnection, Postgres, QueryBuilder}; +use uuid::Uuid; + +pub(super) const MAX_TARGETS: usize = 10_000; + +/// Preserve the caller's existing bound: agent rows, or identities including the human. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum DiscoveryLimit { + AgentRows, + TargetKeys, +} + +/// Fresh human and direct-agent identities, retaining each agent's community. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +pub struct UserDeletionTargets { + /// The human remains the global discovery root. + pub human: String, + /// Agent authority applies only in the recorded community. + pub agents: Vec<(Uuid, String)>, +} + +impl UserDeletionTargets { + /// Sorted distinct identities. Global callers must retain community pairs + /// when authorizing deletion; this flattened list alone grants no authority. + pub fn pubkeys(&self) -> Vec { + let mut keys = vec![self.human.clone()]; + keys.extend(self.agents.iter().map(|(_, key)| key.clone())); + keys.sort(); + keys.dedup(); + keys + } +} + +/// Read current direct ownership in the caller's transaction. No membership or +/// active-profile filter: deactivated profiles remain evidence until cleanup ends. +/// Missing profiles grant no agent authority, and agent ownership is not recursive. +/// `lock` retains FOR SHARE locks until the caller ends its transaction; callers +/// still own write admission and the offline/stopped-writer operating contract. +/// With `community: None` and `DiscoveryLimit::TargetKeys`, callers must pass +/// `lock: false`: this query groups profiles by agent, and PostgreSQL does not +/// allow FOR SHARE with GROUP BY. Use community-scoped discovery for row locking. +pub(super) async fn discover( + conn: &mut PgConnection, + human: &str, + community: Option, + lock: bool, + limit: DiscoveryLimit, +) -> Result { + let human = normalize_user_deletion_pubkey(human)?; + // Media historically limits distinct identities, not community profiles. + // Group those profiles before LIMIT so an agent's communities are never truncated. + let grouped = community.is_none() && limit == DiscoveryLimit::TargetKeys; + let mut query = QueryBuilder::::new(if grouped { + "SELECT array_agg(community_id ORDER BY community_id), encode(pubkey,'hex') FROM users WHERE agent_owner_pubkey=decode(" + } else { + "SELECT ARRAY[community_id], encode(pubkey,'hex') FROM users WHERE agent_owner_pubkey=decode(" + }); + query + .push_bind(human.clone()) + .push(", 'hex') AND pubkey<>decode(") + .push_bind(human.clone()) + .push(", 'hex')"); + if let Some(community) = community { + query.push(" AND community_id=").push_bind(community); + } + if grouped { + query.push(" GROUP BY pubkey ORDER BY pubkey"); + } else { + query.push(" ORDER BY community_id, pubkey"); + } + query.push(" LIMIT ").push_bind((MAX_TARGETS + 1) as i64); + if lock { + query.push(" FOR SHARE"); + } + let rows: Vec<(Vec, String)> = query.build_query_as().fetch_all(conn).await?; + let count = rows.len() + usize::from(limit == DiscoveryLimit::TargetKeys); + if count > MAX_TARGETS { + return Err(DbError::DeletionSafety( + "user deletion ownership exceeds target limit (10000); no partial scope returned" + .into(), + )); + } + let mut agents: Vec<_> = rows + .into_iter() + .flat_map(|(communities, key)| { + communities + .into_iter() + .map(move |community| (community, key.clone())) + }) + .collect(); + agents.sort(); + Ok(UserDeletionTargets { human, agents }) +} + +#[cfg(test)] +#[path = "agent_ownership_postgres_tests.rs"] +mod postgres_tests; diff --git a/crates/buzz-db/src/store/user_deletion/agent_ownership_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/agent_ownership_postgres_tests.rs new file mode 100644 index 00000000000..c90cd66e69b --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/agent_ownership_postgres_tests.rs @@ -0,0 +1,299 @@ +//! Shared ownership contract exercised through all four production handlers. +use super::*; +use crate::user_deletion::{ + account_batches::AccountBatchOptions, content_batches::ContentBatchOptions, + profile_batches::ProfileBatchOptions, ExecutionMode, +}; +use nostr::ToBech32; +use serde_json::Value; + +struct Fixture { + db: crate::Db, + communities: [Uuid; 3], + human: String, + other: String, + agent: String, +} + +impl Fixture { + async fn new() -> Self { + let pool = sqlx::PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + let f = Self { + db: crate::Db::from_pool(pool), + communities: std::array::from_fn(|_| Uuid::new_v4()), + human: nostr::Keys::generate().public_key().to_hex(), + other: nostr::Keys::generate().public_key().to_hex(), + agent: nostr::Keys::generate().public_key().to_hex(), + }; + for community in f.communities { + sqlx::query("INSERT INTO communities(id,host) VALUES ($1,$2)") + .bind(community) + .bind(format!("{community}.example.org")) + .execute(f.db.pool()) + .await + .unwrap(); + for key in [&f.human, &f.other] { + sqlx::query("INSERT INTO users(community_id,pubkey) VALUES ($1,decode($2,'hex'))") + .bind(community) + .bind(key) + .execute(f.db.pool()) + .await + .unwrap(); + } + } + for (community, owner) in [(f.communities[0], &f.human), (f.communities[1], &f.other)] { + // Neither membership nor activation determines ownership. + sqlx::query("INSERT INTO users(community_id,pubkey,agent_owner_pubkey,deactivated_at) VALUES ($1,decode($2,'hex'),decode($3,'hex'),now())") + .bind(community).bind(&f.agent).bind(owner).execute(f.db.pool()).await.unwrap(); + } + f + } + + async fn assert_handlers(&self, owned: Option) { + let store = self.db.user_deletion_store(); + let media = self.db.user_media_targets(&self.human).await.unwrap(); + assert_eq!( + media.agents, + owned + .map(|c| (c, self.agent.clone())) + .into_iter() + .collect::>() + ); + let scope = store.generate_account_scope(&self.human).await.unwrap(); + for community in self.communities { + let mut expected = vec![self.human.clone()]; + if Some(community) == owned { + expected.push(self.agent.clone()); + } + expected.sort(); + let mut saved = scope + .communities + .iter() + .find(|c| c.community == community) + .unwrap() + .pubkeys + .clone(); + saved.sort(); + assert_eq!(saved, expected); + let mut output = Vec::new(); + store + .run_message_batches( + &ContentBatchOptions { + community, + pubkey: self.human.clone(), + relay_pubkey: None, + batch_size: 100, + max_items: 100, + }, + ExecutionMode::ReadOnly, + None, + &mut output, + ) + .await + .unwrap(); + assert_eq!( + records(&output)[0]["target_pubkeys"], + serde_json::json!(expected) + ); + output.clear(); + store + .run_account_batches( + &AccountBatchOptions { + community, + pubkey: self.human.clone(), + batch_size: 100, + max_items: 100, + }, + ExecutionMode::ReadOnly, + &mut output, + None, + ) + .await + .unwrap(); + let mut account: Vec = records(&output) + .into_iter() + .filter(|r| r["record"] == "account_batches_start") + .map(|r| r["pubkey"].as_str().unwrap().to_owned()) + .collect(); + account.sort(); + assert_eq!(account, expected); + let profile = store + .run_profile_batches( + &ProfileBatchOptions { + community, + pubkey: self.human.clone(), + relay_pubkeys: vec![], + batch_size: 100, + max_items: 100, + }, + false, + None, + &mut Vec::new(), + ) + .await + .unwrap(); + assert_eq!(profile.target_pubkeys, expected); + } + } +} + +fn records(output: &[u8]) -> Vec { + std::str::from_utf8(output) + .unwrap() + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect() +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn every_handler_discovers_the_same_current_community_agents_on_retry() { + let f = Fixture::new().await; + f.assert_handlers(Some(f.communities[0])).await; + sqlx::query("UPDATE users SET agent_owner_pubkey=CASE WHEN community_id=$1 THEN decode($2,'hex') ELSE decode($3,'hex') END WHERE pubkey=decode($4,'hex')") + .bind(f.communities[0]).bind(&f.other).bind(&f.human).bind(&f.agent) + .execute(f.db.pool()).await.unwrap(); + f.assert_handlers(Some(f.communities[1])).await; + sqlx::query("DELETE FROM users WHERE pubkey=decode($1,'hex')") + .bind(&f.agent) + .execute(f.db.pool()) + .await + .unwrap(); + f.assert_handlers(None).await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn discovery_is_direct_normalized_and_holds_the_callers_row_locks() { + let f = Fixture::new().await; + let nested = nostr::Keys::generate().public_key().to_hex(); + sqlx::query("INSERT INTO users(community_id,pubkey,agent_owner_pubkey) VALUES ($1,decode($2,'hex'),decode($3,'hex'))") + .bind(f.communities[0]).bind(&nested).bind(&f.agent).execute(f.db.pool()).await.unwrap(); + let npub = nostr::PublicKey::parse(&f.human) + .unwrap() + .to_bech32() + .unwrap(); + let mut tx = f.db.pool().begin().await.unwrap(); + let targets = discover( + &mut tx, + &npub, + Some(f.communities[0]), + true, + DiscoveryLimit::TargetKeys, + ) + .await + .unwrap(); + assert_eq!(targets.human, f.human); + assert_eq!(targets.agents, vec![(f.communities[0], f.agent.clone())]); + assert!(!targets + .agents + .contains(&(f.communities[1], f.agent.clone()))); + assert!(!targets.agents.contains(&(f.communities[0], nested.clone()))); + let mut transfer = f.db.pool().begin().await.unwrap(); + sqlx::query("SET LOCAL lock_timeout='50ms'") + .execute(&mut *transfer) + .await + .unwrap(); + let error = sqlx::query("UPDATE users SET agent_owner_pubkey=decode($1,'hex') WHERE community_id=$2 AND pubkey=decode($3,'hex')") + .bind(&f.other).bind(f.communities[0]).bind(&f.agent).execute(&mut *transfer).await.unwrap_err(); + assert_eq!( + error.as_database_error().unwrap().code().as_deref(), + Some("55P03") + ); + transfer.rollback().await.unwrap(); + tx.rollback().await.unwrap(); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn discovery_preserves_each_callers_original_limit_without_truncating_communities() { + let f = Fixture::new().await; + sqlx::query("INSERT INTO users(community_id,pubkey,agent_owner_pubkey) SELECT c,decode(lpad(to_hex(n),64,'0'),'hex'),decode($3,'hex') FROM unnest(ARRAY[$1::uuid,$2::uuid]) c CROSS JOIN generate_series(1,5000) n") + .bind(f.communities[0]).bind(f.communities[1]).bind(&f.human) + .execute(f.db.pool()).await.unwrap(); + let media = f.db.user_media_targets(&f.human).await.unwrap(); + assert_eq!(media.agents.len(), 10001); + assert_eq!(media.pubkeys().len(), 5002); + assert!(media + .agents + .contains(&(f.communities[1], format!("{:064x}", 5000)))); + sqlx::query("INSERT INTO users(community_id,pubkey,agent_owner_pubkey) SELECT $1,decode(lpad(to_hex(n),64,'0'),'hex'),decode($2,'hex') FROM generate_series(5001,9998) n") + .bind(f.communities[0]).bind(&f.human).execute(f.db.pool()).await.unwrap(); + assert_eq!( + f.db.user_media_targets(&f.human) + .await + .unwrap() + .pubkeys() + .len(), + MAX_TARGETS + ); + let mut tx = f.db.pool().begin().await.unwrap(); + assert_eq!( + discover( + &mut tx, + &f.human, + Some(f.communities[0]), + false, + DiscoveryLimit::TargetKeys + ) + .await + .unwrap() + .pubkeys() + .len(), + MAX_TARGETS + ); + tx.rollback().await.unwrap(); + sqlx::query("INSERT INTO users(community_id,pubkey,agent_owner_pubkey) VALUES ($1,decode($2,'hex'),decode($3,'hex'))") + .bind(f.communities[0]).bind(format!("{:064x}", 9999)).bind(&f.human) + .execute(f.db.pool()).await.unwrap(); + let mut tx = f.db.pool().begin().await.unwrap(); + assert_eq!( + discover( + &mut tx, + &f.human, + Some(f.communities[0]), + false, + DiscoveryLimit::AgentRows + ) + .await + .unwrap() + .agents + .len(), + MAX_TARGETS + ); + for community in [None, Some(f.communities[0])] { + assert!(discover( + &mut tx, + &f.human, + community, + false, + DiscoveryLimit::TargetKeys + ) + .await + .unwrap_err() + .to_string() + .contains("no partial scope")); + } + assert!( + discover(&mut tx, &f.human, None, false, DiscoveryLimit::AgentRows) + .await + .is_err() + ); + tx.rollback().await.unwrap(); + sqlx::query("INSERT INTO users(community_id,pubkey,agent_owner_pubkey) VALUES ($1,decode($2,'hex'),decode($3,'hex'))") + .bind(f.communities[0]).bind(format!("{:064x}", 10000)).bind(&f.human) + .execute(f.db.pool()).await.unwrap(); + let mut tx = f.db.pool().begin().await.unwrap(); + assert!(discover( + &mut tx, + &f.human, + Some(f.communities[0]), + false, + DiscoveryLimit::AgentRows + ) + .await + .is_err()); + tx.rollback().await.unwrap(); +} diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/agents_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/content_batches/agents_postgres_tests.rs index 5a4589993f6..8e494ab279d 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/agents_postgres_tests.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/agents_postgres_tests.rs @@ -441,7 +441,7 @@ async fn target_discovery_handles_no_agents_and_rejects_overflow_without_output( .run_message_batches(&options, mode, None, &mut output) .await .unwrap_err(); - assert!(error.to_string().contains("target key limit")); + assert!(error.to_string().contains("ownership exceeds target limit")); assert!(output.is_empty()); } assert_eq!(snapshot_rows(&pool, community, "users").await.len(), 10001); diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs b/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs index f685d96f0c3..88201b96f49 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs @@ -30,7 +30,7 @@ const KINDS: &[i32] = &[ 30175, 30176, 30178, 30030, 30180, 30621, ]; const PAGE_SIZE: i64 = 100; -const MAX_TARGETS: usize = 10_000; +use super::agent_ownership::MAX_TARGETS; const EVENT_COLUMNS: &str = "e.id,e.created_at,e.channel_id,e.kind,e.tags"; /// Scope and bounds for standalone preview or explicitly requested deletion. diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/ownership.rs b/crates/buzz-db/src/store/user_deletion/content_batches/ownership.rs index 38e394ad935..7fddb521f6e 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/ownership.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/ownership.rs @@ -7,24 +7,18 @@ pub(super) async fn targets( subject: &str, lock: bool, ) -> Result>> { - let query = if lock { - "SELECT pubkey FROM users WHERE community_id=$1 AND agent_owner_pubkey=decode($2,'hex') ORDER BY pubkey LIMIT $3 FOR SHARE" - } else { - "SELECT pubkey FROM users WHERE community_id=$1 AND agent_owner_pubkey=decode($2,'hex') ORDER BY pubkey LIMIT $3" - }; - let mut keys: Vec> = sqlx::query_scalar(query) - .bind(community) - .bind(subject) - .bind((MAX_TARGETS + 1) as i64) - .fetch_all(conn) - .await?; - keys.push(hex::decode(subject).map_err(|_| invalid("invalid target key"))?); - keys.sort(); - keys.dedup(); - if keys.len() > MAX_TARGETS { - return Err(invalid("content target key limit exceeded (10,000)")); - } - Ok(keys) + super::super::agent_ownership::discover( + conn, + subject, + Some(community), + lock, + super::super::agent_ownership::DiscoveryLimit::TargetKeys, + ) + .await? + .pubkeys() + .iter() + .map(|key| hex::decode(key).map_err(|_| invalid("invalid target key"))) + .collect() } pub(super) async fn excluded( diff --git a/crates/buzz-db/src/store/user_deletion/media.rs b/crates/buzz-db/src/store/user_deletion/media.rs index e21ef9f96cf..f3f1f2b7955 100644 --- a/crates/buzz-db/src/store/user_deletion/media.rs +++ b/crates/buzz-db/src/store/user_deletion/media.rs @@ -1,60 +1,76 @@ //! Bounded upload evidence queries for user media cleanup. use crate::{Db, DbError, Result}; +use uuid::Uuid; -const MAX_MEDIA_TARGETS: usize = 10_000; +use super::agent_ownership::{self, UserDeletionTargets, MAX_TARGETS}; + +impl UserDeletionTargets { + fn communities(&self) -> Vec { + self.agents + .iter() + .map(|(community, _)| *community) + .collect() + } + + fn agent_keys(&self) -> Result>> { + self.agents.iter().map(|(_, key)| decode_key(key)).collect() + } +} + +fn decode_key(key: &str) -> Result> { + hex::decode(super::normalize_user_deletion_pubkey(key)?) + .map_err(|error| DbError::InvalidData(error.to_string())) +} const CANDIDATES_SQL: &str = r#"WITH candidates AS MATERIALIZED (SELECT sha256 FROM ( SELECT sha256 COLLATE "C" AS sha256 FROM media_uploaders - WHERE pubkey = ANY($1::bytea[]) AND sha256 COLLATE "C" > $2 + WHERE pubkey = ANY($1::bytea[]) + AND (pubkey = $4 OR (community_id, pubkey) IN (SELECT * FROM unnest($5::uuid[], $6::bytea[]))) + AND sha256 COLLATE "C" > $2 UNION SELECT object_id COLLATE "C" AS sha256 FROM audit_log WHERE action = 'media_uploaded' AND actor_pubkey = ANY($1::bytea[]) + AND (actor_pubkey = $4 OR (community_id, actor_pubkey) IN (SELECT * FROM unnest($5::uuid[], $6::bytea[]))) AND object_id COLLATE "C" > $2 ) uploads ORDER BY sha256 COLLATE "C" LIMIT $3) SELECT sha256, EXISTS ( SELECT 1 FROM media_uploaders m - WHERE m.sha256 = candidates.sha256 COLLATE "default" AND m.pubkey <> ALL($1::bytea[]) + WHERE m.sha256 = candidates.sha256 COLLATE "default" AND NOT (m.pubkey = $4 OR (m.community_id, m.pubkey) IN (SELECT * FROM unnest($5::uuid[], $6::bytea[]))) ) OR EXISTS ( SELECT 1 FROM audit_log a WHERE a.action = 'media_uploaded' AND a.object_id = candidates.sha256 COLLATE "default" - AND a.actor_pubkey <> ALL($1::bytea[]) + AND NOT (a.actor_pubkey = $4 OR (a.community_id, a.actor_pubkey) IN (SELECT * FROM unnest($5::uuid[], $6::bytea[]))) ) AS shared FROM candidates ORDER BY sha256 COLLATE "C""#; impl Db { - /// Resolve the human and their directly owned agents once across communities. - /// Every returned key is a global media target, including its uploads elsewhere. - pub async fn user_media_targets(&self, pubkey: &str) -> Result> { - let pubkey = super::normalize_user_deletion_pubkey(pubkey)?; + /// Fetch direct agent ownership per community on every invocation and retry. + pub async fn user_media_targets(&self, pubkey: &str) -> Result { + let human = super::normalize_user_deletion_pubkey(pubkey)?; let mut tx = self.pool().begin().await?; sqlx::query("SET LOCAL statement_timeout = '120s'") .execute(&mut *tx) .await?; - let keys: Vec = sqlx::query_scalar( - "SELECT key FROM ( - SELECT $1::text AS key - UNION - SELECT encode(pubkey, 'hex') FROM users - WHERE agent_owner_pubkey = decode($1, 'hex') - ) targets ORDER BY key LIMIT $2", + let targets = agent_ownership::discover( + &mut tx, + &human, + None, + false, + agent_ownership::DiscoveryLimit::TargetKeys, ) - .bind(pubkey) - .bind((MAX_MEDIA_TARGETS + 1) as i64) - .fetch_all(&mut *tx) .await?; - validate_keys(&keys)?; tx.commit().await?; - Ok(keys) + Ok(targets) } /// Page through target upload hashes and classify sharing across all communities. /// An empty cursor starts the scan. Storage-only claims are discovered separately. pub async fn user_media_candidates( &self, - pubkeys: &[String], + targets: &UserDeletionTargets, after: &str, limit: u16, ) -> Result> { - let keys = validate_keys(pubkeys)?; + let keys = validate_keys(&targets.pubkeys())?; if !(1..=500).contains(&limit) { return Err(DbError::InvalidData( "media page size must be 1..=500".into(), @@ -71,6 +87,9 @@ impl Db { .bind(keys) .bind(after) .bind(i64::from(limit)) + .bind(decode_key(&targets.human)?) + .bind(targets.communities()) + .bind(targets.agent_keys()?) .fetch_all(&mut *tx) .await?; for (hash, _) in &hashes { @@ -84,10 +103,10 @@ impl Db { /// Call this for storage-discovered candidates too, before deleting anything. pub async fn user_media_shared_hashes( &self, - pubkeys: &[String], + targets: &UserDeletionTargets, hashes: &[String], ) -> Result> { - let keys = validate_keys(pubkeys)?; + validate_keys(&targets.pubkeys())?; if hashes.len() > 500 { return Err(DbError::InvalidData( "media evidence batch exceeds 500 hashes".into(), @@ -104,15 +123,17 @@ impl Db { r#"SELECT candidate FROM unnest($2::text[]) AS candidates(candidate) WHERE EXISTS ( SELECT 1 FROM media_uploaders - WHERE sha256 = candidate AND pubkey <> ALL($1::bytea[]) + WHERE sha256 = candidate AND NOT (pubkey = $1 OR (community_id, pubkey) IN (SELECT * FROM unnest($3::uuid[], $4::bytea[]))) ) OR EXISTS ( SELECT 1 FROM audit_log WHERE action = 'media_uploaded' AND object_id = candidate - AND actor_pubkey <> ALL($1::bytea[]) + AND NOT (actor_pubkey = $1 OR (community_id, actor_pubkey) IN (SELECT * FROM unnest($3::uuid[], $4::bytea[]))) ) ORDER BY candidate COLLATE "C""#, ) - .bind(keys) + .bind(decode_key(&targets.human)?) .bind(hashes) + .bind(targets.communities()) + .bind(targets.agent_keys()?) .fetch_all(&mut *tx) .await?; tx.commit().await?; @@ -121,14 +142,21 @@ impl Db { /// Remove the target set's ownership rows only after storage cleanup succeeds. /// Audit history and publication moderation records are retained. - pub async fn remove_user_media_uploader(&self, pubkeys: &[String], hash: &str) -> Result { - let keys = validate_keys(pubkeys)?; + pub async fn remove_user_media_uploader( + &self, + targets: &UserDeletionTargets, + hash: &str, + ) -> Result { + validate_keys(&targets.pubkeys())?; validate_hash(hash)?; Ok(sqlx::query( - "DELETE FROM media_uploaders WHERE pubkey = ANY($1::bytea[]) AND sha256 = $2", + "DELETE FROM media_uploaders WHERE sha256 = $2 + AND (pubkey = $1 OR (community_id, pubkey) IN (SELECT * FROM unnest($3::uuid[], $4::bytea[])))", ) - .bind(keys) + .bind(decode_key(&targets.human)?) .bind(hash) + .bind(targets.communities()) + .bind(targets.agent_keys()?) .execute(self.pool()) .await? .rows_affected()) @@ -136,7 +164,7 @@ impl Db { } fn validate_keys(pubkeys: &[String]) -> Result>> { - if pubkeys.is_empty() || pubkeys.len() > MAX_MEDIA_TARGETS { + if pubkeys.is_empty() || pubkeys.len() > MAX_TARGETS { return Err(DbError::InvalidData( "media target set must contain 1..=10000 keys".into(), )); @@ -215,7 +243,7 @@ mod postgres_tests { sqlx::query("INSERT INTO media_uploaders(community_id, sha256, pubkey) VALUES ($1, $2, decode($3, 'hex'))") .bind(community).bind(format!("{:064x}", 502)).bind(&bob) .execute(&pool).await.unwrap(); - let keys = vec![alice.clone()]; + let keys = db.user_media_targets(&alice).await.unwrap(); let first = db.user_media_candidates(&keys, "", 500).await.unwrap(); assert_eq!(first.len(), 500); assert_eq!(first[0], (format!("{:064x}", 1), false)); @@ -257,7 +285,7 @@ mod postgres_tests { #[tokio::test] #[ignore = "requires Postgres"] - async fn owned_agents_form_one_global_media_target_set() { + async fn direct_agents_retain_community_scope_and_upload_history() { use nostr::nips::nip19::ToBech32; let pool = sqlx::PgPool::connect(&crate::test_support::database_url()) .await @@ -305,9 +333,10 @@ mod postgres_tests { .unwrap(); let mut expected = vec![alice.clone(), agent.clone()]; expected.sort(); - assert_eq!(keys, expected); // Duplicate/deactivated profiles still yield one agent key. + assert_eq!(keys.pubkeys(), expected); + assert_eq!(keys.agents.len(), 2); // Deactivated profiles retain ownership for retries. assert_eq!( - db.user_media_targets(&agent).await.unwrap(), + db.user_media_targets(&agent).await.unwrap().pubkeys(), vec![agent.clone()] ); let hashes: Vec<_> = (1..=5).map(|n| format!("{n:064x}")).collect(); @@ -397,9 +426,14 @@ mod postgres_tests { .await .unwrap() .contains(&(hashes[0].clone(), false))); - assert!(db.user_media_candidates(&[], "", 500).await.is_err()); assert!(db - .remove_user_media_uploader(&["invalid".into()], &hashes[0]) + .remove_user_media_uploader( + &UserDeletionTargets { + human: "invalid".into(), + agents: vec![] + }, + &hashes[0] + ) .await .is_err()); } @@ -408,3 +442,7 @@ mod postgres_tests { #[cfg(test)] #[path = "media_query_plan_postgres_tests.rs"] mod query_plan_postgres_tests; + +#[cfg(test)] +#[path = "media_ownership_postgres_tests.rs"] +mod ownership_postgres_tests; diff --git a/crates/buzz-db/src/store/user_deletion/media_ownership_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/media_ownership_postgres_tests.rs new file mode 100644 index 00000000000..d9e8235d340 --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/media_ownership_postgres_tests.rs @@ -0,0 +1,121 @@ +//! Same agent identity has independent ownership in each community. +use super::*; + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn community_ownership_controls_candidates_sharing_removal_and_fresh_retry() { + let pool = sqlx::PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + let db = Db::from_pool(pool.clone()); + let alice = nostr::Keys::generate().public_key().to_hex(); + let bob = nostr::Keys::generate().public_key().to_hex(); + let agent = nostr::Keys::generate().public_key().to_hex(); + let nested_agent = nostr::Keys::generate().public_key().to_hex(); + let communities = [Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()]; + for community in communities { + sqlx::query("INSERT INTO communities(id, host) VALUES ($1, $2)") + .bind(community) + .bind(format!("{community}.example.org")) + .execute(&pool) + .await + .unwrap(); + } + for community in communities { + for key in [&alice, &bob] { + sqlx::query("INSERT INTO users(community_id, pubkey) VALUES ($1, decode($2, 'hex'))") + .bind(community) + .bind(key) + .execute(&pool) + .await + .unwrap(); + } + } + for (community, key, owner) in [ + (communities[0], &agent, &alice), + (communities[1], &agent, &bob), + (communities[0], &nested_agent, &agent), + ] { + sqlx::query("INSERT INTO users(community_id, pubkey, agent_owner_pubkey) VALUES ($1, decode($2, 'hex'), decode($3, 'hex'))") + .bind(community).bind(key).bind(owner).execute(&pool).await.unwrap(); + } + let hashes: Vec<_> = (1..=7).map(|n| format!("{n:064x}")).collect(); + for (community, index, key) in [ + (0, 0, &agent), + (1, 0, &agent), // Conflicting community protects shared blob. + (0, 1, &agent), + (2, 1, &agent), // Missing profile also protects shared blob. + (1, 2, &agent), // Outside-only upload is not a candidate. + (0, 3, &agent), // Exclusive owned upload is selected. + (0, 4, &nested_agent), // Direct ownership only; no recursive expansion. + (0, 5, &alice), // Outside audit evidence protects this human upload. + ] { + sqlx::query("INSERT INTO media_uploaders(community_id, sha256, pubkey) VALUES ($1, $2, decode($3, 'hex'))") + .bind(communities[community]).bind(&hashes[index]).bind(key).execute(&pool).await.unwrap(); + } + for (seq, community, index) in [(1_i64, 0, 6), (2, 1, 5), (3, 1, 2), (4, 2, 1)] { + sqlx::query( + "INSERT INTO audit_log(community_id, seq, hash, action, actor_pubkey, object_id) + VALUES ($1, $2, decode($3, 'hex'), 'media_uploaded', decode($4, 'hex'), $5)", + ) + .bind(communities[community]) + .bind(seq) + .bind(format!("{seq:064x}")) + .bind(&agent) + .bind(&hashes[index]) + .execute(&pool) + .await + .unwrap(); + } + let targets = db.user_media_targets(&alice).await.unwrap(); + assert_eq!(targets.agents, vec![(communities[0], agent.clone())]); + assert_eq!( + db.user_media_candidates(&targets, "", 500).await.unwrap(), + [0, 1, 3, 5, 6].map(|i| (hashes[i].clone(), [0, 1, 5].contains(&i))) + ); + assert_eq!( + db.user_media_shared_hashes(&targets, &hashes) + .await + .unwrap(), + [0, 1, 2, 4, 5].map(|i| hashes[i].clone()) + ); + for index in [0, 1] { + assert_eq!( + db.remove_user_media_uploader(&targets, &hashes[index]) + .await + .unwrap(), + 1 + ); + let remaining: Vec = + sqlx::query_scalar("SELECT community_id FROM media_uploaders WHERE sha256 = $1") + .bind(&hashes[index]) + .fetch_all(&pool) + .await + .unwrap(); + assert_eq!(remaining, vec![communities[index + 1]]); + } + // Ownership transfers between runs; the same pubkey list must not hide the changed community. + sqlx::query("UPDATE users SET agent_owner_pubkey = CASE WHEN community_id = $1 THEN decode($2, 'hex') ELSE decode($3, 'hex') END WHERE pubkey = decode($4, 'hex')") + .bind(communities[0]).bind(&bob).bind(&alice).bind(&agent).execute(&pool).await.unwrap(); + let retry = db.user_media_targets(&alice).await.unwrap(); + assert_eq!(retry.pubkeys(), targets.pubkeys()); + assert_eq!(retry.agents, vec![(communities[1], agent.clone())]); + let candidates = db.user_media_candidates(&retry, "", 500).await.unwrap(); + assert!(candidates.iter().any(|(hash, _)| hash == &hashes[2])); + assert!(!candidates + .iter() + .any(|(hash, _)| hash == &hashes[3] || hash == &hashes[6])); + // Removing ownership evidence excludes the agent on the next invocation. + sqlx::query("DELETE FROM users WHERE pubkey IN (decode($1, 'hex'), decode($2, 'hex'))") + .bind(&agent) + .bind(&nested_agent) + .execute(&pool) + .await + .unwrap(); + assert!(db + .user_media_targets(&alice) + .await + .unwrap() + .agents + .is_empty()); +} diff --git a/crates/buzz-db/src/store/user_deletion/media_query_plan_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/media_query_plan_postgres_tests.rs index cf62ad8fa6b..1608f9d4694 100644 --- a/crates/buzz-db/src/store/user_deletion/media_query_plan_postgres_tests.rs +++ b/crates/buzz-db/src/store/user_deletion/media_query_plan_postgres_tests.rs @@ -17,6 +17,15 @@ async fn media_discovery_and_sharing_use_indexes_without_current_membership() { .unwrap(); let alice = nostr::Keys::generate().public_key().to_hex(); let bob = nostr::Keys::generate().public_key().to_hex(); + let agent = nostr::Keys::generate().public_key().to_hex(); + sqlx::query("INSERT INTO users(community_id,pubkey) VALUES ($1,decode($2,'hex'))") + .bind(community) + .bind(&alice) + .execute(&pool) + .await + .unwrap(); + sqlx::query("INSERT INTO users(community_id,pubkey,agent_owner_pubkey) VALUES ($1,decode($2,'hex'),decode($3,'hex'))") + .bind(community).bind(&agent).bind(&alice).execute(&pool).await.unwrap(); // Membership was removed; retained attribution is still authoritative. sqlx::query("INSERT INTO relay_members(community_id, pubkey, role) VALUES ($1, $2, 'member')") .bind(community) @@ -54,7 +63,7 @@ async fn media_discovery_and_sharing_use_indexes_without_current_membership() { ) .bind(community) .bind(format!("{:064x}", 40002)) - .bind(&alice) + .bind(&agent) .execute(&pool) .await .unwrap(); @@ -63,10 +72,9 @@ async fn media_discovery_and_sharing_use_indexes_without_current_membership() { .await .unwrap(); let db = Db::from_pool(pool.clone()); - let actual = db - .user_media_candidates(std::slice::from_ref(&alice), "", 500) - .await - .unwrap(); + let targets = db.user_media_targets(&alice).await.unwrap(); + assert_eq!(targets.agents, vec![(community, agent)]); + let actual = db.user_media_candidates(&targets, "", 500).await.unwrap(); assert_eq!( actual, [1, 20001, 40001, 40002].map(|n| (format!("{n:064x}"), n < 40000)) @@ -74,9 +82,12 @@ async fn media_discovery_and_sharing_use_indexes_without_current_membership() { // Only a fixed EXPLAIN prefix and the production SQL constant are concatenated. let explain = format!("EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) {CANDIDATES_SQL}"); let plan: Value = sqlx::query_scalar(sqlx::AssertSqlSafe(explain.as_str())) - .bind(validate_keys(&[alice]).unwrap()) + .bind(validate_keys(&targets.pubkeys()).unwrap()) .bind("") .bind(500_i64) + .bind(decode_key(&targets.human).unwrap()) + .bind(targets.communities()) + .bind(targets.agent_keys().unwrap()) .fetch_one(&pool) .await .unwrap(); diff --git a/crates/buzz-db/src/store/user_deletion/mod.rs b/crates/buzz-db/src/store/user_deletion/mod.rs index b519293f049..e4a50a06d8e 100644 --- a/crates/buzz-db/src/store/user_deletion/mod.rs +++ b/crates/buzz-db/src/store/user_deletion/mod.rs @@ -3,6 +3,7 @@ use crate::Db; use sqlx::PgPool; /// Bounded cleanup of one human's community account records. pub mod account_batches; +mod agent_ownership; /// Ordered user and owned-agent content cleanup in read-only and delete modes. pub mod content_batches; mod discovery; @@ -10,6 +11,7 @@ mod inventory; mod media; /// Standalone, offline profile cleanup with read-only preview. pub mod profile_batches; +pub use agent_ownership::UserDeletionTargets; mod requests; pub use discovery::normalize_user_deletion_pubkey; pub use inventory::UserDeletionInventory; diff --git a/crates/buzz-db/src/store/user_deletion/profile_batches/ownership.rs b/crates/buzz-db/src/store/user_deletion/profile_batches/ownership.rs index 9b2b63ce0db..3418a2558ea 100644 --- a/crates/buzz-db/src/store/user_deletion/profile_batches/ownership.rs +++ b/crates/buzz-db/src/store/user_deletion/profile_batches/ownership.rs @@ -1,5 +1,4 @@ use super::*; -use std::collections::BTreeSet; pub(super) async fn targets( conn: &mut PgConnection, @@ -7,22 +6,15 @@ pub(super) async fn targets( human: &str, lock: bool, ) -> Result> { - let sql = if lock { - "SELECT pubkey FROM users WHERE community_id=$1 AND agent_owner_pubkey=decode($2,'hex') ORDER BY pubkey LIMIT 10001 FOR SHARE" - } else { - "SELECT pubkey FROM users WHERE community_id=$1 AND agent_owner_pubkey=decode($2,'hex') ORDER BY pubkey LIMIT 10001" - }; - let agents: Vec> = sqlx::query_scalar(sql) - .bind(community) - .bind(human) - .fetch_all(conn) - .await?; - let mut targets = BTreeSet::from([human.to_owned()]); - targets.extend(agents.iter().map(hex::encode)); - if targets.len() > 10_000 { - return Err(invalid("profile target limit exceeded (10000)")); - } - Ok(targets.into_iter().collect()) + Ok(super::super::agent_ownership::discover( + conn, + human, + Some(community), + lock, + super::super::agent_ownership::DiscoveryLimit::TargetKeys, + ) + .await? + .pubkeys()) } pub(super) async fn recheck( diff --git a/crates/buzz-deletion/src/user/media.rs b/crates/buzz-deletion/src/user/media.rs index 8b1e507bee9..0bd4fc5a398 100644 --- a/crates/buzz-deletion/src/user/media.rs +++ b/crates/buzz-deletion/src/user/media.rs @@ -1,6 +1,6 @@ //! User media cleanup. Both modes use the same upload-only inventory. use anyhow::{bail, Context, Result}; -use buzz_db::{Db, DbConfig}; +use buzz_db::{user_deletion::UserDeletionTargets, Db, DbConfig}; use buzz_media::{ classify_key, KeyClass, MediaStorage, ObjectVersionEntry, ObjectVersionKind, ObjectVersionRef, ObjectVersionsPage, UploadRecord, UPLOAD_RECORD_VERSION, @@ -19,7 +19,7 @@ const MAX_STORAGE_PAGES: usize = 100_000; /// Direct media-handler arguments; no workflow request is needed. #[derive(Debug, clap::Args)] pub struct Args { - /// Human public key (hex or npub). Includes owned agents across all communities. + /// Human public key (hex or npub). Includes agents only where currently owned. #[arg(long, value_parser = buzz_db::user_deletion::normalize_user_deletion_pubkey)] pub pubkey: String, /// Print selected files without changing the database or storage (default). @@ -71,24 +71,37 @@ pub(super) async fn handle_with_storage( // Fakes replace only external DB/storage boundaries; the tests run the same // candidate collection, prefix scans, bounded inventory and deletion loop. trait Database { - async fn targets(&self, pubkey: &str) -> Result>; - async fn candidates(&self, pubkeys: &[String], after: &str) -> Result>; - async fn shared(&self, pubkeys: &[String], hashes: &[String]) -> Result>; - async fn remove(&self, pubkeys: &[String], hash: &str) -> Result; + async fn targets(&self, pubkey: &str) -> Result; + async fn candidates( + &self, + pubkeys: &UserDeletionTargets, + after: &str, + ) -> Result>; + async fn shared(&self, pubkeys: &UserDeletionTargets, hashes: &[String]) + -> Result>; + async fn remove(&self, pubkeys: &UserDeletionTargets, hash: &str) -> Result; } impl Database for Db { - async fn targets(&self, pubkey: &str) -> Result> { + async fn targets(&self, pubkey: &str) -> Result { Ok(self.user_media_targets(pubkey).await?) } - async fn candidates(&self, pubkeys: &[String], after: &str) -> Result> { + async fn candidates( + &self, + pubkeys: &UserDeletionTargets, + after: &str, + ) -> Result> { Ok(self .user_media_candidates(pubkeys, after, PAGE_SIZE) .await?) } - async fn shared(&self, pubkeys: &[String], hashes: &[String]) -> Result> { + async fn shared( + &self, + pubkeys: &UserDeletionTargets, + hashes: &[String], + ) -> Result> { Ok(self.user_media_shared_hashes(pubkeys, hashes).await?) } - async fn remove(&self, pubkeys: &[String], hash: &str) -> Result { + async fn remove(&self, pubkeys: &UserDeletionTargets, hash: &str) -> Result { Ok(self.remove_user_media_uploader(pubkeys, hash).await?) } } @@ -151,7 +164,7 @@ async fn run_handler_with_inventory( mut inventory: Inventory, ) -> Result { let keys = db.targets(pubkey).await?; - let keys_set: HashSet<_> = keys.iter().cloned().collect(); + let keys_set: HashSet<_> = keys.agents.iter().cloned().collect(); let mut after = String::new(); loop { let page = db.candidates(&keys, &after).await?; @@ -166,7 +179,15 @@ async fn run_handler_with_inventory( } // Finish discovery before classifying storage-only candidates. Historical // upload claims may precede the target's claim in the listing. - scan_storage(media, &keys_set, &mut inventory, "_uploads/", true).await?; + scan_storage( + media, + &keys.human, + &keys_set, + &mut inventory, + "_uploads/", + true, + ) + .await?; after.clear(); loop { let hashes = inventory.unchecked_candidates(&after).await?; @@ -181,8 +202,24 @@ async fn run_handler_with_inventory( if !inventory.candidates("").await?.is_empty() { // These community-first namespaces cannot be looked up by hash alone. // Keep complete historical coverage, including removed communities. - scan_storage(media, &keys_set, &mut inventory, "_uploads/", false).await?; - scan_storage(media, &keys_set, &mut inventory, "_meta/", false).await?; + scan_storage( + media, + &keys.human, + &keys_set, + &mut inventory, + "_uploads/", + false, + ) + .await?; + scan_storage( + media, + &keys.human, + &keys_set, + &mut inventory, + "_meta/", + false, + ) + .await?; } after.clear(); loop { @@ -194,7 +231,15 @@ async fn run_handler_with_inventory( for (hash, _) in page { // The dot excludes other hash families while covering all blob // extensions, thumbnails, historical versions and delete markers. - scan_storage(media, &keys_set, &mut inventory, &format!("{hash}."), false).await?; + scan_storage( + media, + &keys.human, + &keys_set, + &mut inventory, + &format!("{hash}."), + false, + ) + .await?; } } inventory.require_immutable_versions().await?; @@ -205,7 +250,8 @@ async fn run_handler_with_inventory( async fn scan_storage( media: &impl Storage, - keys_set: &HashSet, + human: &str, + keys_set: &HashSet<(uuid::Uuid, String)>, inventory: &mut Inventory, prefix: &str, candidates_only: bool, @@ -260,10 +306,11 @@ async fn scan_storage( let owner = buzz_db::user_deletion::normalize_user_deletion_pubkey( &record.uploader_id, )?; - if candidates_only && keys_set.contains(&owner) { + let targeted = owner == human || keys_set.contains(&(*community, owner)); + if candidates_only && targeted { candidates.push(hash.clone()); } - if !candidates_only && !keys_set.contains(&owner) { + if !candidates_only && !targeted { shared.push(hash.clone()); } } @@ -334,6 +381,7 @@ pub(super) fn configured_storage() -> Result { mod tests { mod capacity; mod claim_versions; + mod ownership; mod s3; use super::*; use clap::Parser; @@ -373,7 +421,7 @@ mod tests { #[derive(Default)] struct FakeDb { - targets: Vec, + targets: Vec<(uuid::Uuid, String)>, target_calls: RefCell, candidates: Vec, shared: Vec, @@ -381,17 +429,20 @@ mod tests { removed: RefCell>, } impl Database for FakeDb { - async fn targets(&self, pubkey: &str) -> Result> { + async fn targets(&self, pubkey: &str) -> Result { *self.target_calls.borrow_mut() += 1; - Ok(if self.targets.is_empty() { - vec![pubkey.to_owned()] - } else { - self.targets.clone() + Ok(UserDeletionTargets { + human: pubkey.to_owned(), + agents: self.targets.clone(), }) } - async fn candidates(&self, keys: &[String], after: &str) -> Result> { + async fn candidates( + &self, + keys: &UserDeletionTargets, + after: &str, + ) -> Result> { if !self.targets.is_empty() { - assert_eq!(keys, self.targets); + assert_eq!(keys.agents, self.targets); } Ok(self .candidates @@ -401,9 +452,13 @@ mod tests { .map(|hash| (hash.clone(), self.shared.contains(hash))) .collect()) } - async fn shared(&self, keys: &[String], hashes: &[String]) -> Result> { + async fn shared( + &self, + keys: &UserDeletionTargets, + hashes: &[String], + ) -> Result> { if !self.targets.is_empty() { - assert_eq!(keys, self.targets); + assert_eq!(keys.agents, self.targets); } self.checked.borrow_mut().extend_from_slice(hashes); Ok(hashes @@ -412,9 +467,9 @@ mod tests { .cloned() .collect()) } - async fn remove(&self, keys: &[String], hash: &str) -> Result { + async fn remove(&self, keys: &UserDeletionTargets, hash: &str) -> Result { if !self.targets.is_empty() { - assert_eq!(keys, self.targets); + assert_eq!(keys.agents, self.targets); } self.removed.borrow_mut().push(hash.into()); Ok(1) @@ -656,7 +711,10 @@ mod tests { async fn combined_targets_share_one_inventory_and_preserve_outside_uploaders() { let hashes: Vec<_> = (1..=5).map(|n| format!("{n:064x}")).collect(); let db = FakeDb { - targets: vec![ALICE.into(), AGENT.into()], + targets: vec![ + (uuid::Uuid::from_u128(1), AGENT.into()), + (uuid::Uuid::from_u128(2), AGENT.into()), + ], candidates: vec![hashes[0].clone()], shared: vec![hashes[3].clone()], // Outside uploader found only in DB. ..Default::default() @@ -677,8 +735,9 @@ mod tests { .await .unwrap(); let report: Value = serde_json::from_slice(&output).unwrap(); - assert_eq!(report["target_pubkeys"], json!([ALICE, AGENT])); + assert_eq!(report["target_pubkeys"], json!([AGENT, ALICE])); assert_eq!(report["summary"], preview); + assert!(report.get("agent_communities").is_none()); let files = report["files"].as_array().unwrap(); assert_eq!(files.len(), 4); assert!(files.iter().all(|file| file.get("owners").is_none())); diff --git a/crates/buzz-deletion/src/user/media/tests/ownership.rs b/crates/buzz-deletion/src/user/media/tests/ownership.rs new file mode 100644 index 00000000000..6d98aa3cb3d --- /dev/null +++ b/crates/buzz-deletion/src/user/media/tests/ownership.rs @@ -0,0 +1,42 @@ +//! Community boundaries through the real media handler. +use super::*; + +#[tokio::test] +async fn agent_claims_in_other_communities_protect_blobs_and_are_not_selected() { + let hashes: Vec<_> = (1..=4).map(|n| format!("{n:064x}")).collect(); + let db = FakeDb { + targets: vec![(uuid::Uuid::from_u128(1), AGENT.into())], + ..Default::default() + }; + let mut media = FakeStorage::default(); + media.upload(&hashes[0], AGENT, 1); // Owned here: delete. + media.upload(&hashes[1], AGENT, 2); // Owned elsewhere or missing evidence: untouched. + media.upload(&hashes[2], ALICE, 1); + media.upload(&hashes[2], AGENT, 2); // Same key outside scope protects shared bytes. + media.upload(&hashes[3], AGENT, 1); + media.upload(&hashes[3], AGENT, 2); // Sharing across communities protects agent's bytes too. + for hash in &hashes { + media.object(format!("{hash}.png"), ObjectVersionKind::Object); + } + let before = media.entries.borrow().clone(); + let preview = run_handler(&db, &media, ALICE, false, &mut Vec::new()) + .await + .unwrap(); + assert_eq!(preview["selected_files"], 3); + assert_eq!(preview["kept_files"], 2); + assert_eq!(*media.entries.borrow(), before); + assert!(db.removed.borrow().is_empty()); + let result = run_handler(&db, &media, ALICE, true, &mut Vec::new()) + .await + .unwrap(); + assert_eq!(result["deleted_versions"], 2); + assert!(media + .deleted + .borrow() + .iter() + .all(|entry| entry.key.contains(&hashes[0]))); + assert_eq!( + *db.removed.borrow(), + vec![hashes[0].clone(), hashes[2].clone(), hashes[3].clone()] + ); +} diff --git a/crates/buzz-deletion/src/user/media_report.rs b/crates/buzz-deletion/src/user/media_report.rs index 2221650df76..a8fbfb880c5 100644 --- a/crates/buzz-deletion/src/user/media_report.rs +++ b/crates/buzz-deletion/src/user/media_report.rs @@ -1,5 +1,5 @@ //! One JSON document, streamed from bounded inventory pages even for large files. -use super::{Database, Inventory, Storage}; +use super::{Database, Inventory, Storage, UserDeletionTargets}; use anyhow::Result; use serde_json::{json, Value}; use std::io::Write; @@ -7,7 +7,7 @@ use std::io::Write; pub(super) async fn execute( db: &impl Database, media: &impl Storage, - pubkeys: &[String], + pubkeys: &UserDeletionTargets, delete: bool, inventory: &mut Inventory, output: &mut impl Write, @@ -17,7 +17,7 @@ pub(super) async fn execute( output, "{{\n \"mode\": \"{mode}\",\n \"target_pubkeys\": " )?; - serde_json::to_writer(&mut *output, pubkeys)?; + serde_json::to_writer(&mut *output, &pubkeys.pubkeys())?; write!(output, ",\n \"files\": [")?; let (mut selected, mut kept, mut deleted_versions) = (0usize, 0usize, 0usize); let mut after = String::new(); diff --git a/crates/buzz-deletion/src/user/worker_postgres_tests/media_retry.rs b/crates/buzz-deletion/src/user/worker_postgres_tests/media_retry.rs index cc56626fd2b..f42027fc902 100644 --- a/crates/buzz-deletion/src/user/worker_postgres_tests/media_retry.rs +++ b/crates/buzz-deletion/src/user/worker_postgres_tests/media_retry.rs @@ -108,3 +108,90 @@ async fn gate_then_media_requires_delete_and_retries_storage_failure_before_comm assert_eq!(fixture.requests.load(Ordering::SeqCst), calls); store.release(&lease).await.unwrap(); } + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn workflow_media_retry_refetches_agent_ownership_before_deleting() { + let fixture = fixture().await; + let human: String = + sqlx::query_scalar("SELECT encode(pubkey, 'hex') FROM media_uploaders WHERE sha256 = $1") + .bind("a".repeat(64)) + .fetch_one(&fixture.pool) + .await + .unwrap(); + let agent = nostr::Keys::generate().public_key().to_hex(); + let bob = nostr::Keys::generate().public_key().to_hex(); + for key in [&human, &bob] { + sqlx::query("INSERT INTO users(community_id, pubkey) VALUES ($1, decode($2, 'hex'))") + .bind(Uuid::from_u128(11)) + .bind(key) + .execute(&fixture.pool) + .await + .unwrap(); + } + sqlx::query("INSERT INTO users(community_id, pubkey, agent_owner_pubkey) VALUES ($1, decode($2, 'hex'), decode($3, 'hex'))") + .bind(Uuid::from_u128(11)).bind(&agent).bind(&human).execute(&fixture.pool).await.unwrap(); + // Retain ownership elsewhere on retry: flattening agent keys would still + // select the upload in community 11 after that community changes owner. + sqlx::query("INSERT INTO users(community_id, pubkey) VALUES ($1, decode($2, 'hex'))") + .bind(Uuid::from_u128(12)) + .bind(&human) + .execute(&fixture.pool) + .await + .unwrap(); + sqlx::query("INSERT INTO users(community_id, pubkey, agent_owner_pubkey) VALUES ($1, decode($2, 'hex'), decode($3, 'hex'))") + .bind(Uuid::from_u128(12)).bind(&agent).bind(&human).execute(&fixture.pool).await.unwrap(); + sqlx::query("UPDATE media_uploaders SET pubkey = decode($1, 'hex') WHERE sha256 = $2") + .bind(&agent) + .bind("a".repeat(64)) + .execute(&fixture.pool) + .await + .unwrap(); + fixture.fail_listing.store(true, Ordering::SeqCst); + run( + &fixture.store, + fixture.id, + "worker-a", + &fixture.options(), + &CancellationToken::new(), + ) + .await + .unwrap_err(); + let failed = fixture.store.inspect(fixture.id).await.unwrap(); + assert_eq!(failed.stage_history[1].status, "failed"); + assert!(!fixture.deleted.load(Ordering::SeqCst)); + sqlx::query( + "UPDATE users SET agent_owner_pubkey = decode($1, 'hex') WHERE pubkey = decode($2, 'hex') AND community_id = $3", + ) + .bind(&bob) + .bind(&agent) + .bind(Uuid::from_u128(11)) + .execute(&fixture.pool) + .await + .unwrap(); + sqlx::query("UPDATE entity_deletion_requests SET next_attempt_at = clock_timestamp() - interval '1 second' WHERE id = $1") + .bind(fixture.id).execute(&fixture.pool).await.unwrap(); + fixture.fail_listing.store(false, Ordering::SeqCst); + run( + &fixture.store, + fixture.id, + "worker-b", + &RunOptions { + next_step: true, + ..fixture.options() + }, + &CancellationToken::new(), + ) + .await + .unwrap(); + let after = fixture.store.inspect(fixture.id).await.unwrap(); + assert_eq!(after.stage_history[1].id, failed.stage_history[1].id); + assert_eq!(after.stage_history[1].status, "completed"); + assert_eq!( + after.stage_history[1].metadata_json["result"]["selected_files"], + 0 + ); + assert_eq!(after.stage_history[2].stage, "purge_content"); + assert!(!fixture.deleted.load(Ordering::SeqCst)); + assert_eq!(fixture.uploader_count().await, 1); +} diff --git a/docs/operator-user-deletion-executor.md b/docs/operator-user-deletion-executor.md index ce9cf44f003..a65c7f672e4 100644 --- a/docs/operator-user-deletion-executor.md +++ b/docs/operator-user-deletion-executor.md @@ -248,9 +248,43 @@ placeholder failures and branching only. Demo media success is synthetic; real r An injected community failure preserves the same retry semantics as before. Ctrl-C releases the worker lease; after an abrupt kill wait for lease expiry. +## Shared agent discovery + +Media, content, account, and profile cleanup use the same discovery utility in +`buzz-db/src/store/user_deletion/agent_ownership.rs`, including account scope +capture. It normalizes the human key, reads current direct ownership from +`users`, and retains `(community_id, agent_pubkey)` pairs. It does not infer +ownership from membership, recurse through agents, or exclude deactivated +profiles. A missing profile grants no agent cleanup authority. + +Every invocation and retry discovers again. Content, account, and profile +handlers use the utility inside their existing batch transactions with row +locks when rechecking ownership. Profile cleanup compares against the identities +that remain after its own committed batches. Media discovers once per invocation +and uses that snapshot through inventory and deletion. Writers must remain +stopped throughout the operation. + +Discovery preserves each caller's existing limits: media, content and profile +allow 10,000 distinct identities including the human; account discovery allows +10,000 agents. Account scope capture retains its existing total-key bound. +Media retains every owned community for each selected agent. Ownership profiles must +remain until all dependent cleanup completes; profile removal goes last. + +Media has no separate cap on `(community_id, agent_pubkey)` pairs. One agent can +contribute a pair for every community where the human owns it, so the identity +limit does not bound the pair count. These pairs are retained in memory, including +the storage-matching hash set, and the full pair arrays are sent with each media +candidate-page query. They are outside the inventory budget described below; +memory use and query payload size grow with the number of owned agent profiles. + ## Media discovery and remaining limits -The target set is the human and directly owned agents across communities. +Every invocation and retry fetches the human's current directly owned agents +from `users`, retaining each `(community_id, agent_pubkey)` pair. The human's +own uploads are global targets; an agent's uploads are targets only in communities +where that human currently owns it. A missing profile or a different owner in +another community does not authorize cleanup there. Ownership rows must remain +until media and other dependent handlers finish. Candidate hashes come from `media_uploaders`, `media_uploaded` audit entries, and storage upload claims. A bounded database query combines candidate discovery with outside-uploader classification. Storage-only candidates receive the same @@ -259,7 +293,9 @@ history filter: relay membership rows can be deleted on departure. Sharing checks span all communities for the selected hashes. Any outside uploader in either database source or an upload-record version protects the -file. No per-file owner-list query is made. +file, including the same agent's uploads in an unowned community. No per-file +owner-list query is made. The report retains its deduplicated `target_pubkeys`; +community ownership is used internally for every media decision. Storage discovery scans `_uploads/` for target claims, then reads candidate claims in a second `_uploads/` listing to protect outside claims encountered