mirror of
https://github.com/block/buzz.git
synced 2026-11-25 02:31:36 +00:00
Add standalone profile cleanup batches
Preview and delete scoped identity data for a user and owned agents. Keep shared archive snapshots signed and preserve other communities. Leave workflow integration and online fencing separate. Co-authored-by: dessert <7d616e7e143e5d408159614dccff1371350a1c1bd36c8de838a45ece5aca0aca@buzz.block.builderlab.xyz> Signed-off-by: Ravneet Arora <rarora@squareup.com>
This commit is contained in:
@@ -3,6 +3,8 @@ use crate::Db;
|
|||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
mod discovery;
|
mod discovery;
|
||||||
mod inventory;
|
mod inventory;
|
||||||
|
/// Standalone, offline profile cleanup with read-only preview.
|
||||||
|
pub mod profile_batches;
|
||||||
mod requests;
|
mod requests;
|
||||||
pub use discovery::normalize_user_deletion_pubkey;
|
pub use discovery::normalize_user_deletion_pubkey;
|
||||||
pub use inventory::UserDeletionInventory;
|
pub use inventory::UserDeletionInventory;
|
||||||
|
|||||||
276
crates/buzz-db/src/store/user_deletion/profile_batches/events.rs
Normal file
276
crates/buzz-db/src/store/user_deletion/profile_batches/events.rs
Normal file
@@ -0,0 +1,276 @@
|
|||||||
|
use super::*;
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use nostr::{Event, EventBuilder, Kind, Tag, Timestamp};
|
||||||
|
use sqlx::Row;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
pub(super) struct Snapshot {
|
||||||
|
signer: String,
|
||||||
|
time: u64,
|
||||||
|
survivors: Arc<Vec<String>>,
|
||||||
|
}
|
||||||
|
pub(super) struct Selected {
|
||||||
|
pub id: Vec<u8>,
|
||||||
|
pub key: Value,
|
||||||
|
pub fingerprint: String,
|
||||||
|
pub snapshot: Option<Snapshot>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn subject(tags: &Value, name: &str) -> Result<String> {
|
||||||
|
let all = tags
|
||||||
|
.as_array()
|
||||||
|
.ok_or_else(|| invalid("profile tags are not an array"))?;
|
||||||
|
let tagged: Vec<_> = all
|
||||||
|
.iter()
|
||||||
|
.filter(|t| t.get(0).and_then(Value::as_str) == Some(name))
|
||||||
|
.collect();
|
||||||
|
if tagged.len() != 1 {
|
||||||
|
return Err(invalid(format!(
|
||||||
|
"profile requires exactly one {name} subject"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
let value = tagged[0]
|
||||||
|
.get(1)
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.ok_or_else(|| invalid("missing profile subject"))?;
|
||||||
|
if value.len() != 64 || !value.bytes().all(|c| c.is_ascii_hexdigit()) {
|
||||||
|
return Err(invalid("malformed profile subject"));
|
||||||
|
}
|
||||||
|
normalize_user_deletion_pubkey(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn select(
|
||||||
|
conn: &mut PgConnection,
|
||||||
|
scope: &Scope,
|
||||||
|
max: u32,
|
||||||
|
) -> Result<Vec<Selected>> {
|
||||||
|
// Scope before payload inspection. Case-insensitive subject comparison covers historical hex.
|
||||||
|
// The statement budget bounds the fallback tag scan; no new schema is required.
|
||||||
|
let candidate_sql="SELECT id,created_at,kind,encode(pubkey,'hex') AS author,channel_id,
|
||||||
|
CASE WHEN pg_column_size(tags)<=65536 THEN tags END AS tags,
|
||||||
|
jsonb_build_object('id',id,'created_at',created_at) AS key,encode(sha256(convert_to(to_jsonb(e)::text,'UTF8')),'hex') AS fingerprint
|
||||||
|
FROM events e WHERE community_id=$1 AND kind IN (0,10100,30177,30179,30382,9035,9036,8002,8003,13535)
|
||||||
|
AND (pubkey=ANY($2::bytea[]) OR EXISTS(SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(tags)='array' THEN tags ELSE '[]'::jsonb END) tag
|
||||||
|
WHERE (tag->>0 IN ('p','d') AND lower(tag->>1)=ANY($3::text[])) OR (tag->>0='consent' AND lower(tag->>2)=ANY($3::text[]))))
|
||||||
|
ORDER BY created_at,id LIMIT $4";
|
||||||
|
// Bound payload memory before materializing candidate tags. The query remains read-only.
|
||||||
|
let budget_sql = format!("SELECT count(*) AS count, COALESCE(sum(pg_column_size(tags)),0)::bigint AS bytes FROM ({candidate_sql}) candidates");
|
||||||
|
let budget = sqlx::query(sqlx::AssertSqlSafe(budget_sql))
|
||||||
|
.bind(scope.community)
|
||||||
|
.bind(&scope.bytes)
|
||||||
|
.bind(&scope.targets)
|
||||||
|
.bind((i64::from(max) + 1).min(65_537))
|
||||||
|
.fetch_one(&mut *conn)
|
||||||
|
.await?;
|
||||||
|
if budget.try_get::<i64, _>("count")? > i64::from(max).min(65_536)
|
||||||
|
|| budget.try_get::<i64, _>("bytes")? > 32 * 1024 * 1024
|
||||||
|
{
|
||||||
|
return Err(invalid(
|
||||||
|
"profile candidates exceed item or 32 MiB payload budget",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let candidates = sqlx::query(candidate_sql)
|
||||||
|
.bind(scope.community)
|
||||||
|
.bind(&scope.bytes)
|
||||||
|
.bind(&scope.targets)
|
||||||
|
.bind((i64::from(max) + 1).min(65_537))
|
||||||
|
.fetch_all(&mut *conn)
|
||||||
|
.await?;
|
||||||
|
if candidates.len() > max as usize {
|
||||||
|
return Err(invalid(
|
||||||
|
"profile candidates exceed max-items; no deletion performed",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let survivors:Vec<String>=sqlx::query_scalar("SELECT pubkey FROM archived_identities WHERE community_id=$1 AND NOT(pubkey=ANY($2::text[])) ORDER BY pubkey LIMIT 10001")
|
||||||
|
.bind(scope.community).bind(&scope.targets).fetch_all(&mut *conn).await?;
|
||||||
|
let survivors = Arc::new(survivors);
|
||||||
|
let mut out: Vec<Selected> = Vec::new();
|
||||||
|
// Every replacement is strictly newer than every current snapshot from that signer.
|
||||||
|
let mut next_time: HashMap<String, u64> = HashMap::new();
|
||||||
|
let mut snapshot_index: HashMap<String, usize> = HashMap::new();
|
||||||
|
for row in candidates {
|
||||||
|
let kind: i32 = row.try_get("kind")?;
|
||||||
|
let author: String = row.try_get("author")?;
|
||||||
|
let tags: Value = row
|
||||||
|
.try_get::<Option<Value>, _>("tags")?
|
||||||
|
.ok_or_else(|| invalid("profile tags exceed 64 KiB"))?;
|
||||||
|
let authored = scope.targets.contains(&author);
|
||||||
|
let mut snapshot = None;
|
||||||
|
let selected = match kind {
|
||||||
|
0 | 10100 => authored,
|
||||||
|
30177 | 30179 => {
|
||||||
|
let agent = subject(&tags, "d")?;
|
||||||
|
if authored && !scope.targets.contains(&agent) {
|
||||||
|
return Err(invalid(
|
||||||
|
"managed definition names an unselected agent; save its inventory first",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if scope.targets.contains(&agent) && author != scope.human {
|
||||||
|
return Err(invalid("managed agent definition belongs to another owner"));
|
||||||
|
}
|
||||||
|
authored && scope.targets.contains(&agent)
|
||||||
|
}
|
||||||
|
30382 => {
|
||||||
|
let target = subject(&tags, "p")?;
|
||||||
|
if target != subject(&tags, "d")? {
|
||||||
|
return Err(invalid("verified profile d/p subjects disagree"));
|
||||||
|
}
|
||||||
|
if scope.targets.contains(&target) {
|
||||||
|
trusted(scope, &author)?;
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
9035 | 9036 => {
|
||||||
|
let target = subject(&tags, "p")?;
|
||||||
|
if authored && !scope.targets.contains(&target) {
|
||||||
|
return Err(invalid("archive request concerns a surviving identity; shared-history disposition required"));
|
||||||
|
}
|
||||||
|
scope.targets.contains(&target)
|
||||||
|
}
|
||||||
|
8002 | 8003 => {
|
||||||
|
let target = subject(&tags, "p")?;
|
||||||
|
if scope.targets.contains(&target) {
|
||||||
|
trusted(scope, &author)?;
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
return Err(invalid("archive delta names a target actor on a surviving identity; shared-history disposition required"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
13535 => {
|
||||||
|
trusted(scope, &author)?;
|
||||||
|
if survivors.len() > 10_000 {
|
||||||
|
return Err(invalid(
|
||||||
|
"archive snapshot exceeds 10000 retained identities",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let previous = if let Some(previous) = next_time.get(&author) {
|
||||||
|
*previous
|
||||||
|
} else {
|
||||||
|
let max_time:Option<DateTime<Utc>>=sqlx::query_scalar("SELECT max(created_at) FROM events WHERE community_id=$1 AND kind=13535 AND pubkey=decode($2,'hex')")
|
||||||
|
.bind(scope.community).bind(&author).fetch_one(&mut *conn).await?;
|
||||||
|
max_time
|
||||||
|
.map_or(0, |t| t.timestamp().max(0) as u64)
|
||||||
|
.max(Timestamp::now().as_secs())
|
||||||
|
};
|
||||||
|
let time = previous
|
||||||
|
.checked_add(1)
|
||||||
|
.ok_or_else(|| invalid("archive snapshot timestamp overflow"))?;
|
||||||
|
next_time.insert(author.clone(), time);
|
||||||
|
snapshot = Some(Snapshot {
|
||||||
|
signer: author.clone(),
|
||||||
|
time,
|
||||||
|
survivors: survivors.clone(),
|
||||||
|
});
|
||||||
|
true
|
||||||
|
}
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
if selected {
|
||||||
|
if row.try_get::<Option<Uuid>, _>("channel_id")?.is_some() {
|
||||||
|
return Err(invalid("channel-bearing profile requires content cleanup"));
|
||||||
|
}
|
||||||
|
if let Some(new_snapshot) = &snapshot {
|
||||||
|
if let Some(previous) =
|
||||||
|
snapshot_index.insert(new_snapshot.signer.clone(), out.len())
|
||||||
|
{
|
||||||
|
out[previous].snapshot = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push(Selected {
|
||||||
|
id: row.try_get("id")?,
|
||||||
|
key: row.try_get("key")?,
|
||||||
|
fingerprint: row.try_get("fingerprint")?,
|
||||||
|
snapshot,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
fn trusted(scope: &Scope, author: &str) -> Result<()> {
|
||||||
|
if !scope.relays.iter().any(|r| r == author) {
|
||||||
|
return Err(invalid("subject profile/archive event has an untrusted relay signer; supply verified --relay-pubkey"));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn sign_snapshots(
|
||||||
|
plan: &Plan,
|
||||||
|
signer: Option<&nostr::Keys>,
|
||||||
|
) -> Result<HashMap<String, Event>> {
|
||||||
|
let mut out = HashMap::new();
|
||||||
|
let Some(signer) = signer else {
|
||||||
|
return Ok(out);
|
||||||
|
};
|
||||||
|
for op in &plan.ops {
|
||||||
|
let Some(snapshot) = &op.snapshot else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if signer.public_key().to_hex() != snapshot.signer {
|
||||||
|
return Err(invalid(
|
||||||
|
"relay signing key does not match archive snapshot signer",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let mut tags = vec![Tag::parse(["-"]).map_err(|_| invalid("invalid archive marker"))?];
|
||||||
|
for p in snapshot.survivors.iter() {
|
||||||
|
tags.push(
|
||||||
|
Tag::parse(["p", p.as_str()]).map_err(|_| invalid("invalid archive subject"))?,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let event = EventBuilder::new(Kind::Custom(13535), "")
|
||||||
|
.tags(tags)
|
||||||
|
.custom_created_at(Timestamp::from(snapshot.time))
|
||||||
|
.sign_with_keys(signer)
|
||||||
|
.map_err(|_| invalid("could not sign archive snapshot"))?;
|
||||||
|
out.insert(op.key.to_string(), event);
|
||||||
|
if out.len() > 64 {
|
||||||
|
return Err(invalid("too many archive signers"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn replace_snapshot(
|
||||||
|
tx: &mut crate::AdmittedTx,
|
||||||
|
scope: &Scope,
|
||||||
|
op: &rows::Operation,
|
||||||
|
replacements: &HashMap<String, Event>,
|
||||||
|
) -> Result<u64> {
|
||||||
|
let event = replacements
|
||||||
|
.get(&op.key.to_string())
|
||||||
|
.ok_or_else(|| invalid("missing signed archive replacement"))?;
|
||||||
|
let current: Vec<String> = sqlx::query_scalar(
|
||||||
|
"SELECT pubkey FROM archived_identities WHERE community_id=$1 ORDER BY pubkey LIMIT 10001",
|
||||||
|
)
|
||||||
|
.bind(scope.community)
|
||||||
|
.fetch_all(tx.conn())
|
||||||
|
.await?;
|
||||||
|
let expected: Vec<String> = event
|
||||||
|
.tags
|
||||||
|
.iter()
|
||||||
|
.filter_map(|t| {
|
||||||
|
let t = t.as_slice();
|
||||||
|
(t.first().map(String::as_str) == Some("p"))
|
||||||
|
.then(|| t.get(1).cloned())
|
||||||
|
.flatten()
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if current != expected {
|
||||||
|
return Err(invalid(
|
||||||
|
"archive membership changed; re-preview before snapshot replacement",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
// A shared event writer preserves the normal insert hooks and replica rules.
|
||||||
|
let removed=sqlx::query("DELETE FROM events e WHERE community_id=$1 AND id=($2->>'id')::bytea AND created_at=($2->>'created_at')::timestamptz AND encode(sha256(convert_to(to_jsonb(e)::text,'UTF8')),'hex')=$3")
|
||||||
|
.bind(scope.community).bind(&op.key).bind(&op.fingerprint).execute(tx.conn()).await?.rows_affected();
|
||||||
|
if removed != 1 {
|
||||||
|
return Ok(removed);
|
||||||
|
}
|
||||||
|
let (_, inserted) = crate::event::insert_event_in_transaction(tx, event, None).await?;
|
||||||
|
if !inserted {
|
||||||
|
return Err(invalid("archive replacement already exists; re-preview"));
|
||||||
|
}
|
||||||
|
Ok(removed)
|
||||||
|
}
|
||||||
266
crates/buzz-db/src/store/user_deletion/profile_batches/mod.rs
Normal file
266
crates/buzz-db/src/store/user_deletion/profile_batches/mod.rs
Normal file
@@ -0,0 +1,266 @@
|
|||||||
|
//! Offline profile erasure. Preview and deletion share the exact immutable plan.
|
||||||
|
//! Writers must remain stopped until the caller's full deletion verification ends.
|
||||||
|
use super::{normalize_user_deletion_pubkey, UserDeletionStore};
|
||||||
|
use crate::{DbError, Result};
|
||||||
|
use serde::Serialize;
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
use sqlx::{Connection, PgConnection};
|
||||||
|
use std::io::Write;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
mod events;
|
||||||
|
mod plan;
|
||||||
|
#[cfg(test)]
|
||||||
|
mod postgres_tests;
|
||||||
|
mod rows;
|
||||||
|
|
||||||
|
/// Explicit scope for standalone profile preview and deletion.
|
||||||
|
pub struct ProfileBatchOptions {
|
||||||
|
/// Surviving community whose profiles are selected.
|
||||||
|
pub community: Uuid,
|
||||||
|
/// Human key as hex or npub.
|
||||||
|
pub pubkey: String,
|
||||||
|
/// Additional previously inventoried agents, retained across retries.
|
||||||
|
pub agent_pubkeys: Vec<String>,
|
||||||
|
/// Explicitly trusted current/historical relay signing keys.
|
||||||
|
pub relay_pubkeys: Vec<String>,
|
||||||
|
/// Row mutations per transaction, 1..=100.
|
||||||
|
pub batch_size: u16,
|
||||||
|
/// Maximum planned mutations, 1..=1,000,000; overflow makes no changes.
|
||||||
|
pub max_items: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Result for this profile scope, never a claim of complete account erasure.
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct ProfileBatchSummary {
|
||||||
|
/// preview_complete or delete_complete, emitted only on success.
|
||||||
|
pub record: &'static str,
|
||||||
|
/// Proposed or committed row mutations.
|
||||||
|
pub items: usize,
|
||||||
|
/// Proposed or committed transactions.
|
||||||
|
pub batches: usize,
|
||||||
|
/// Frozen human/agent keys. Supply agent keys on retries after row removal.
|
||||||
|
pub target_pubkeys: Vec<String>,
|
||||||
|
/// Always false; the independent final verifier owns that claim.
|
||||||
|
pub account_erasure_complete: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Scope {
|
||||||
|
community: Uuid,
|
||||||
|
human: String,
|
||||||
|
targets: Vec<String>,
|
||||||
|
bytes: Vec<Vec<u8>>,
|
||||||
|
relays: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Plan {
|
||||||
|
scope: Scope,
|
||||||
|
ops: Vec<rows::Operation>,
|
||||||
|
blockers: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UserDeletionStore {
|
||||||
|
/// Preview or execute a standalone profile plan with stopped writers.
|
||||||
|
///
|
||||||
|
/// No workflow is enabled, lease acquired or deletion journal modified.
|
||||||
|
/// `relay_secret` is required only to replace a shared archive snapshot;
|
||||||
|
/// it must match that snapshot's trusted signer and is never printed.
|
||||||
|
pub async fn run_profile_batches(
|
||||||
|
&self,
|
||||||
|
options: &ProfileBatchOptions,
|
||||||
|
delete: bool,
|
||||||
|
relay_secret: Option<&str>,
|
||||||
|
writer: &mut impl Write,
|
||||||
|
) -> Result<ProfileBatchSummary> {
|
||||||
|
if !(1..=100).contains(&options.batch_size) || !(1..=1_000_000).contains(&options.max_items)
|
||||||
|
{
|
||||||
|
return Err(invalid(
|
||||||
|
"batch-size must be 1..100 and max-items 1..1000000",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let mut conn = self.pool.acquire().await?.detach();
|
||||||
|
// Detached connection closes on every return/cancellation; settings never leak to the pool.
|
||||||
|
sqlx::query("SET statement_timeout='30s'")
|
||||||
|
.execute(&mut conn)
|
||||||
|
.await?;
|
||||||
|
sqlx::query("SET lock_timeout='3s'")
|
||||||
|
.execute(&mut conn)
|
||||||
|
.await?;
|
||||||
|
sqlx::query("SET TIME ZONE 'UTC'")
|
||||||
|
.execute(&mut conn)
|
||||||
|
.await?;
|
||||||
|
let mut snapshot = conn.begin().await?;
|
||||||
|
sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY")
|
||||||
|
.execute(&mut *snapshot)
|
||||||
|
.await?;
|
||||||
|
let plan = plan::build(&mut snapshot, options).await?;
|
||||||
|
snapshot.rollback().await?;
|
||||||
|
line(
|
||||||
|
writer,
|
||||||
|
&json!({"record":"profile_batches_start", "community":options.community,
|
||||||
|
"target_pubkeys":plan.scope.targets, "read_only":!delete,
|
||||||
|
"blockers":plan.blockers,
|
||||||
|
"retained":["deletion records", "replay protection", "repositories"],
|
||||||
|
"external_work":["media objects", "client caches", "online admission and writer fencing"],
|
||||||
|
"account_erasure_complete":false}),
|
||||||
|
)?;
|
||||||
|
let signer = if delete && plan.ops.iter().any(|o| o.snapshot.is_some()) {
|
||||||
|
Some(
|
||||||
|
nostr::Keys::parse(relay_secret.ok_or_else(|| {
|
||||||
|
invalid("archive snapshot replacement requires BUZZ_RELAY_PRIVATE_KEY")
|
||||||
|
})?)
|
||||||
|
.map_err(|_| invalid("invalid relay signing key"))?,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
if delete && !plan.blockers.is_empty() {
|
||||||
|
return Err(invalid(
|
||||||
|
"profile prerequisites unresolved; see printed blockers; no changes made",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
// Sign before the first mutation: a missing/wrong key cannot strand a partial deletion.
|
||||||
|
let replacements = events::sign_snapshots(&plan, signer.as_ref())?;
|
||||||
|
let mut groups = Vec::new();
|
||||||
|
let mut start = 0;
|
||||||
|
let mut count = 0;
|
||||||
|
for (index, op) in plan.ops.iter().enumerate() {
|
||||||
|
if op.cost() > usize::from(options.batch_size) {
|
||||||
|
return Err(invalid(
|
||||||
|
"archive replacement needs batch-size of at least 2",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if count + op.cost() > usize::from(options.batch_size) {
|
||||||
|
groups.push(&plan.ops[start..index]);
|
||||||
|
start = index;
|
||||||
|
count = 0;
|
||||||
|
}
|
||||||
|
count += op.cost();
|
||||||
|
}
|
||||||
|
if start < plan.ops.len() {
|
||||||
|
groups.push(&plan.ops[start..]);
|
||||||
|
}
|
||||||
|
let items: usize = plan.ops.iter().map(rows::Operation::cost).sum();
|
||||||
|
if items > options.max_items as usize {
|
||||||
|
return Err(invalid(
|
||||||
|
"profile mutations exceed max-items; no changes made",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let mut batches = 0;
|
||||||
|
for (batch_index, batch) in groups.iter().enumerate() {
|
||||||
|
line(
|
||||||
|
writer,
|
||||||
|
&json!({"record":"proposed_batch", "number":batch_index+1,
|
||||||
|
"items":batch.iter().map(rows::Operation::description).collect::<Vec<_>>()}),
|
||||||
|
)?;
|
||||||
|
if delete {
|
||||||
|
let mut raw = self.pool.begin().await?;
|
||||||
|
for setting in [
|
||||||
|
"SET LOCAL statement_timeout='30s'",
|
||||||
|
"SET LOCAL lock_timeout='3s'",
|
||||||
|
"SET LOCAL TIME ZONE 'UTC'",
|
||||||
|
] {
|
||||||
|
sqlx::query(setting).execute(&mut *raw).await?;
|
||||||
|
}
|
||||||
|
lock(&mut raw, &plan.scope).await?;
|
||||||
|
let mut tx = crate::AdmittedTx::admit(
|
||||||
|
raw,
|
||||||
|
&crate::deletion::DeletionStore::new(self.pool.clone()),
|
||||||
|
buzz_core::CommunityId::from_uuid(plan.scope.community),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
plan::validate_ownership(tx.conn(), &plan.scope).await?;
|
||||||
|
for op in *batch {
|
||||||
|
rows::apply(&mut tx, &plan.scope, op, &replacements).await?;
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
line(
|
||||||
|
writer,
|
||||||
|
&json!({"record":"batch_committed","number":batch_index+1,"items":batch.iter().map(rows::Operation::cost).sum::<usize>()}),
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
batches += 1;
|
||||||
|
}
|
||||||
|
if !plan.blockers.is_empty() {
|
||||||
|
return Err(invalid(
|
||||||
|
"preview has unresolved prerequisites; no completion marker",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if delete {
|
||||||
|
// Replan using the saved targets: identity deletion must not shrink verification scope.
|
||||||
|
let check = ProfileBatchOptions {
|
||||||
|
community: options.community,
|
||||||
|
pubkey: plan.scope.human.clone(),
|
||||||
|
agent_pubkeys: plan
|
||||||
|
.scope
|
||||||
|
.targets
|
||||||
|
.iter()
|
||||||
|
.filter(|p| *p != &plan.scope.human)
|
||||||
|
.cloned()
|
||||||
|
.collect(),
|
||||||
|
relay_pubkeys: plan.scope.relays.clone(),
|
||||||
|
batch_size: options.batch_size,
|
||||||
|
max_items: options.max_items,
|
||||||
|
};
|
||||||
|
let mut tx = conn.begin().await?;
|
||||||
|
lock(&mut tx, &plan.scope).await?;
|
||||||
|
let remaining = plan::build(&mut tx, &check).await?;
|
||||||
|
if !remaining.ops.is_empty() || !remaining.blockers.is_empty() {
|
||||||
|
return Err(invalid(
|
||||||
|
"profile rows or dependencies remain; rerun with the printed target keys",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
}
|
||||||
|
let summary = ProfileBatchSummary {
|
||||||
|
record: if delete {
|
||||||
|
"delete_complete"
|
||||||
|
} else {
|
||||||
|
"preview_complete"
|
||||||
|
},
|
||||||
|
items,
|
||||||
|
batches,
|
||||||
|
target_pubkeys: plan.scope.targets,
|
||||||
|
account_erasure_complete: false,
|
||||||
|
};
|
||||||
|
line(writer, &summary)?;
|
||||||
|
conn.close().await?;
|
||||||
|
Ok(summary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn lock(conn: &mut PgConnection, scope: &Scope) -> Result<()> {
|
||||||
|
sqlx::query("SELECT pg_advisory_xact_lock_shared($1)")
|
||||||
|
.bind(crate::deletion::SCHEMA_DESTRUCTION_LOCK_KEY)
|
||||||
|
.execute(&mut *conn)
|
||||||
|
.await?;
|
||||||
|
sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))")
|
||||||
|
.bind(crate::deletion::community_deletion_lock_key(
|
||||||
|
buzz_core::CommunityId::from_uuid(scope.community),
|
||||||
|
))
|
||||||
|
.execute(&mut *conn)
|
||||||
|
.await?;
|
||||||
|
let active: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM communities WHERE id=$1 AND deletion_state='active' AND deleted_at IS NULL)")
|
||||||
|
.bind(scope.community).fetch_one(conn).await?;
|
||||||
|
if !active {
|
||||||
|
return Err(invalid(
|
||||||
|
"community is absent or undergoing whole-community deletion",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn invalid(message: impl Into<String>) -> DbError {
|
||||||
|
DbError::DeletionSafety(message.into())
|
||||||
|
}
|
||||||
|
fn line(writer: &mut impl Write, value: &impl Serialize) -> Result<()> {
|
||||||
|
let bytes = serde_json::to_vec(value)?;
|
||||||
|
if bytes.len() > 2 * 1024 * 1024 {
|
||||||
|
return Err(invalid("output exceeds 2 MiB; reduce batch-size"));
|
||||||
|
}
|
||||||
|
writer
|
||||||
|
.write_all(&bytes)
|
||||||
|
.and_then(|()| writer.write_all(b"\n"))
|
||||||
|
.and_then(|()| writer.flush())
|
||||||
|
.map_err(|e| invalid(format!("profile batch output failed: {e}")))
|
||||||
|
}
|
||||||
128
crates/buzz-db/src/store/user_deletion/profile_batches/plan.rs
Normal file
128
crates/buzz-db/src/store/user_deletion/profile_batches/plan.rs
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
use super::*;
|
||||||
|
use sqlx::Row;
|
||||||
|
use std::collections::BTreeSet;
|
||||||
|
|
||||||
|
pub(super) async fn build(conn: &mut PgConnection, options: &ProfileBatchOptions) -> Result<Plan> {
|
||||||
|
let human = normalize_user_deletion_pubkey(&options.pubkey)?;
|
||||||
|
let mut targets = BTreeSet::from([human.clone()]);
|
||||||
|
for p in &options.agent_pubkeys {
|
||||||
|
targets.insert(normalize_user_deletion_pubkey(p)?);
|
||||||
|
}
|
||||||
|
// Match the content command's cross-community ownership discovery; mutation stays tenant-scoped.
|
||||||
|
let agents: Vec<Vec<u8>> = sqlx::query_scalar("SELECT DISTINCT pubkey FROM users WHERE agent_owner_pubkey=decode($1,'hex') ORDER BY pubkey LIMIT 10001")
|
||||||
|
.bind(&human).fetch_all(&mut *conn).await?;
|
||||||
|
targets.extend(agents.iter().map(hex::encode));
|
||||||
|
if targets.len() > 10_000 {
|
||||||
|
return Err(invalid("profile target limit exceeded (10000)"));
|
||||||
|
}
|
||||||
|
let targets: Vec<String> = targets.into_iter().collect();
|
||||||
|
let relays: Vec<String> = options
|
||||||
|
.relay_pubkeys
|
||||||
|
.iter()
|
||||||
|
.map(|p| normalize_user_deletion_pubkey(p))
|
||||||
|
.collect::<Result<_>>()?;
|
||||||
|
if relays.iter().any(|p| targets.contains(p)) {
|
||||||
|
return Err(invalid("target keys and trusted relay keys must differ"));
|
||||||
|
}
|
||||||
|
let bytes = targets
|
||||||
|
.iter()
|
||||||
|
.map(|p| hex::decode(p).map_err(|_| invalid("invalid target key")))
|
||||||
|
.collect::<Result<_>>()?;
|
||||||
|
let scope = Scope {
|
||||||
|
community: options.community,
|
||||||
|
human,
|
||||||
|
targets,
|
||||||
|
bytes,
|
||||||
|
relays,
|
||||||
|
};
|
||||||
|
let active: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM communities WHERE id=$1 AND deletion_state='active' AND deleted_at IS NULL)")
|
||||||
|
.bind(scope.community).fetch_one(&mut *conn).await?;
|
||||||
|
if !active {
|
||||||
|
return Err(invalid(
|
||||||
|
"community is absent or undergoing whole-community deletion",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
validate_ownership(conn, &scope).await?;
|
||||||
|
let blockers = dependencies(conn, &scope).await?;
|
||||||
|
let mut plan = Plan {
|
||||||
|
scope,
|
||||||
|
ops: Vec::new(),
|
||||||
|
blockers,
|
||||||
|
};
|
||||||
|
let selected = events::select(conn, &plan.scope, options.max_items).await?;
|
||||||
|
let ids: Vec<Vec<u8>> = selected.iter().map(|e| e.id.clone()).collect();
|
||||||
|
// Threaded/channel-bearing data belongs to content cleanup; never break a surviving discussion.
|
||||||
|
let threaded: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM thread_metadata WHERE community_id=$1 AND (event_id=ANY($2::bytea[]) OR parent_event_id=ANY($2::bytea[]) OR root_event_id=ANY($2::bytea[])))")
|
||||||
|
.bind(plan.scope.community).bind(&ids).fetch_one(&mut *conn).await?;
|
||||||
|
if threaded {
|
||||||
|
plan.blockers
|
||||||
|
.push("selected profiles have thread dependencies; content cleanup required".into());
|
||||||
|
}
|
||||||
|
for table in rows::CHILDREN {
|
||||||
|
rows::collect(conn, &mut plan, table, &ids, options.max_items).await?;
|
||||||
|
}
|
||||||
|
let mut snapshots = Vec::new();
|
||||||
|
for event in selected {
|
||||||
|
let op = rows::Operation {
|
||||||
|
table: &rows::EVENTS,
|
||||||
|
key: event.key,
|
||||||
|
fingerprint: event.fingerprint,
|
||||||
|
snapshot: event.snapshot,
|
||||||
|
};
|
||||||
|
if op.snapshot.is_some() {
|
||||||
|
snapshots.push(op);
|
||||||
|
} else {
|
||||||
|
rows::push(&mut plan, op, options.max_items)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows::collect(conn, &mut plan, &rows::HEADS, &[], options.max_items).await?;
|
||||||
|
rows::collect(conn, &mut plan, &rows::ARCHIVES, &[], options.max_items).await?;
|
||||||
|
// Archive rows go first, then snapshots; retries can find stale snapshots while identities remain.
|
||||||
|
for op in snapshots {
|
||||||
|
rows::push(&mut plan, op, options.max_items)?;
|
||||||
|
}
|
||||||
|
let before_users = plan.ops.len();
|
||||||
|
rows::collect(conn, &mut plan, &rows::USERS, &[], options.max_items).await?;
|
||||||
|
let human_bytea = format!("\\x{}", plan.scope.human);
|
||||||
|
plan.ops[before_users..].sort_by_key(|op| op.key["pubkey"].as_str() == Some(&human_bytea));
|
||||||
|
Ok(plan)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn validate_ownership(conn: &mut PgConnection, scope: &Scope) -> Result<()> {
|
||||||
|
let conflict: bool=sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM users WHERE community_id=$1 AND \
|
||||||
|
((pubkey=ANY($2::bytea[]) AND pubkey<>decode($3,'hex') AND agent_owner_pubkey IS DISTINCT FROM decode($3,'hex')) \
|
||||||
|
OR (agent_owner_pubkey=ANY($2::bytea[]) AND NOT(pubkey=ANY($2::bytea[])))))")
|
||||||
|
.bind(scope.community).bind(&scope.bytes).bind(&scope.human).fetch_one(conn).await?;
|
||||||
|
if conflict {
|
||||||
|
return Err(invalid(
|
||||||
|
"agent ownership changed, is missing, or has unselected dependents",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn dependencies(conn: &mut PgConnection, scope: &Scope) -> Result<Vec<String>> {
|
||||||
|
let mut blockers = Vec::new();
|
||||||
|
// Static fragments only. These checks also run immediately before final user removal.
|
||||||
|
for (table, selector) in [
|
||||||
|
("api_tokens","owner_pubkey=ANY($2::bytea[])"),
|
||||||
|
("workflows","owner_pubkey=ANY($2::bytea[])"),
|
||||||
|
("subscriptions","owner_pubkey=ANY($2::bytea[])"),
|
||||||
|
("channel_members","pubkey=ANY($2::bytea[])"),
|
||||||
|
("relay_members","pubkey=ANY(SELECT encode(k,'hex') FROM unnest($2::bytea[]) k)"),
|
||||||
|
("events","pubkey=ANY($2::bytea[]) AND kind NOT IN (0,10100,30177,30179,9035,9036)"),
|
||||||
|
("archived_identities","NOT(pubkey=ANY(SELECT encode(k,'hex') FROM unnest($2::bytea[]) k)) AND (actor=ANY(SELECT encode(k,'hex') FROM unnest($2::bytea[]) k) OR replaced_by=ANY(SELECT encode(k,'hex') FROM unnest($2::bytea[]) k))"),
|
||||||
|
] {
|
||||||
|
let sql=format!("SELECT EXISTS(SELECT 1 FROM {table} WHERE community_id=$1 AND ({selector}))");
|
||||||
|
let exists:bool=sqlx::query_scalar(sqlx::AssertSqlSafe(sql)).bind(scope.community).bind(&scope.bytes).fetch_one(&mut *conn).await?;
|
||||||
|
if exists {blockers.push(format!("{table}: content/account cleanup or shared-reference disposition required"));}
|
||||||
|
}
|
||||||
|
// Avoid silently erasing an ownership link through the users self-FK.
|
||||||
|
let rows=sqlx::query("SELECT encode(pubkey,'hex') AS pubkey FROM users WHERE community_id=$1 AND agent_owner_pubkey=ANY($2::bytea[]) AND NOT(pubkey=ANY($2::bytea[])) LIMIT 1")
|
||||||
|
.bind(scope.community).bind(&scope.bytes).fetch_all(conn).await?;
|
||||||
|
if let Some(row) = rows.first() {
|
||||||
|
let _: String = row.try_get("pubkey")?;
|
||||||
|
blockers.push("unselected agent depends on a target identity".into());
|
||||||
|
}
|
||||||
|
Ok(blockers)
|
||||||
|
}
|
||||||
@@ -0,0 +1,431 @@
|
|||||||
|
use super::*;
|
||||||
|
use nostr::{Event, EventBuilder, Keys, Kind, Tag, Timestamp};
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
struct Fixture {
|
||||||
|
pool: PgPool,
|
||||||
|
store: UserDeletionStore,
|
||||||
|
community: Uuid,
|
||||||
|
elsewhere: Uuid,
|
||||||
|
human: Keys,
|
||||||
|
agent: Keys,
|
||||||
|
other: Keys,
|
||||||
|
relay: Keys,
|
||||||
|
}
|
||||||
|
impl Fixture {
|
||||||
|
async fn new() -> Self {
|
||||||
|
let pool = PgPool::connect(&crate::test_support::database_url())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let store = crate::Db::from_pool(pool.clone()).user_deletion_store();
|
||||||
|
let f = Self {
|
||||||
|
pool,
|
||||||
|
store,
|
||||||
|
community: Uuid::new_v4(),
|
||||||
|
elsewhere: Uuid::new_v4(),
|
||||||
|
human: Keys::generate(),
|
||||||
|
agent: Keys::generate(),
|
||||||
|
other: Keys::generate(),
|
||||||
|
relay: Keys::generate(),
|
||||||
|
};
|
||||||
|
for c in [f.community, f.elsewhere] {
|
||||||
|
sqlx::query("INSERT INTO communities(id,host) VALUES($1,$2)")
|
||||||
|
.bind(c)
|
||||||
|
.bind(format!("{c}.example.org"))
|
||||||
|
.execute(&f.pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
for k in [&f.human, &f.agent, &f.other] {
|
||||||
|
sqlx::query("INSERT INTO users(community_id,pubkey,display_name) VALUES($1,$2,'profile fixture')").bind(c).bind(k.public_key().to_bytes().as_slice()).execute(&f.pool).await.unwrap();
|
||||||
|
}
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE users SET agent_owner_pubkey=$2 WHERE community_id=$1 AND pubkey=$3",
|
||||||
|
)
|
||||||
|
.bind(c)
|
||||||
|
.bind(f.human.public_key().to_bytes().as_slice())
|
||||||
|
.bind(f.agent.public_key().to_bytes().as_slice())
|
||||||
|
.execute(&f.pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
f
|
||||||
|
}
|
||||||
|
fn options(&self, batch_size: u16) -> ProfileBatchOptions {
|
||||||
|
ProfileBatchOptions {
|
||||||
|
community: self.community,
|
||||||
|
pubkey: self.human.public_key().to_hex(),
|
||||||
|
agent_pubkeys: vec![self.agent.public_key().to_hex()],
|
||||||
|
relay_pubkeys: vec![self.relay.public_key().to_hex()],
|
||||||
|
batch_size,
|
||||||
|
max_items: 1000,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async fn event(
|
||||||
|
&self,
|
||||||
|
c: Uuid,
|
||||||
|
key: &Keys,
|
||||||
|
kind: u16,
|
||||||
|
tags: Vec<Vec<String>>,
|
||||||
|
content: &str,
|
||||||
|
) -> Event {
|
||||||
|
let event = EventBuilder::new(Kind::Custom(kind), content)
|
||||||
|
.tags(tags.into_iter().map(|v| Tag::parse(v).unwrap()))
|
||||||
|
.custom_created_at(Timestamp::now())
|
||||||
|
.sign_with_keys(key)
|
||||||
|
.unwrap();
|
||||||
|
sqlx::query("INSERT INTO events(community_id,id,pubkey,created_at,kind,tags,content,sig) VALUES($1,$2,$3,$4,$5,$6,$7,$8)")
|
||||||
|
.bind(c).bind(event.id.to_bytes().as_slice()).bind(event.pubkey.to_bytes().as_slice())
|
||||||
|
.bind(chrono::DateTime::from_timestamp(event.created_at.as_secs() as i64,0).unwrap())
|
||||||
|
.bind(i32::from(kind)).bind(serde_json::to_value(&event.tags).unwrap()).bind(&event.content).bind(event.sig.serialize().as_slice())
|
||||||
|
.execute(&self.pool).await.unwrap();
|
||||||
|
event
|
||||||
|
}
|
||||||
|
async fn profiles(&self) {
|
||||||
|
for c in [self.community, self.elsewhere] {
|
||||||
|
self.event(c, &self.human, 0, vec![], "human profile").await;
|
||||||
|
self.event(c, &self.agent, 10100, vec![], "agent profile")
|
||||||
|
.await;
|
||||||
|
self.event(c, &self.other, 0, vec![], "surviving profile")
|
||||||
|
.await;
|
||||||
|
self.event(
|
||||||
|
c,
|
||||||
|
&self.human,
|
||||||
|
30177,
|
||||||
|
vec![vec!["d".into(), self.agent.public_key().to_hex()]],
|
||||||
|
"configuration",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
let subject = self.human.public_key().to_hex();
|
||||||
|
let event = self
|
||||||
|
.event(
|
||||||
|
self.community,
|
||||||
|
&self.relay,
|
||||||
|
30382,
|
||||||
|
vec![
|
||||||
|
vec!["d".into(), subject.clone()],
|
||||||
|
vec!["p".into(), subject.clone()],
|
||||||
|
],
|
||||||
|
"",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
sqlx::query("INSERT INTO nip_fi_profile_heads(community_id,pubkey,issuer,issued_at,event) VALUES($1,$2,'https://issuer.example.org',1,$3)")
|
||||||
|
.bind(self.community).bind(&subject).bind(serde_json::to_value(&event).unwrap()).execute(&self.pool).await.unwrap();
|
||||||
|
sqlx::query("INSERT INTO event_mentions(community_id,pubkey_hex,event_id,event_created_at,event_kind) VALUES($1,$2,$3,now(),30382)")
|
||||||
|
.bind(self.community).bind(&subject).bind(event.id.to_bytes().as_slice()).execute(&self.pool).await.unwrap();
|
||||||
|
for key in [&self.human, &self.other] {
|
||||||
|
sqlx::query("INSERT INTO archived_identities(community_id,pubkey,consent_path,actor,request_event_id) VALUES($1,$2,'self',$2,$3)")
|
||||||
|
.bind(self.community).bind(key.public_key().to_hex()).bind("a".repeat(64)).execute(&self.pool).await.unwrap();
|
||||||
|
}
|
||||||
|
self.event(
|
||||||
|
self.community,
|
||||||
|
&self.relay,
|
||||||
|
13535,
|
||||||
|
vec![
|
||||||
|
vec!["-".into()],
|
||||||
|
vec!["p".into(), subject],
|
||||||
|
vec!["p".into(), self.other.public_key().to_hex()],
|
||||||
|
],
|
||||||
|
"",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn export(pool: &PgPool) -> BTreeMap<String, Value> {
|
||||||
|
let tables: Vec<String> = sqlx::query_scalar(
|
||||||
|
"SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename",
|
||||||
|
)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let mut result = BTreeMap::new();
|
||||||
|
for table in tables {
|
||||||
|
let sql=format!("SELECT COALESCE(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text),'[]'::jsonb) FROM public.\"{}\" t",table.replace('"',"\"\""));
|
||||||
|
result.insert(
|
||||||
|
table,
|
||||||
|
sqlx::query_scalar(sqlx::AssertSqlSafe(sql))
|
||||||
|
.fetch_one(pool)
|
||||||
|
.await
|
||||||
|
.unwrap(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
#[ignore = "requires Postgres"]
|
||||||
|
async fn preview_delete_retry_preserve_other_identities_and_communities() {
|
||||||
|
let f = Fixture::new().await;
|
||||||
|
f.profiles().await;
|
||||||
|
let before = export(&f.pool).await;
|
||||||
|
let mut preview = Vec::new();
|
||||||
|
let opts = f.options(2);
|
||||||
|
let expected = f
|
||||||
|
.store
|
||||||
|
.run_profile_batches(&opts, false, None, &mut preview)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(before, export(&f.pool).await, "preview changed database");
|
||||||
|
assert!(expected.items > 2);
|
||||||
|
assert!(expected.batches > 1);
|
||||||
|
let output = String::from_utf8(preview).unwrap();
|
||||||
|
assert!(output.contains("replace_archive_snapshot"));
|
||||||
|
assert!(!output.contains("configuration"));
|
||||||
|
assert!(!output.contains("human profile"));
|
||||||
|
let mut deletion = Vec::new();
|
||||||
|
let actual = f
|
||||||
|
.store
|
||||||
|
.run_profile_batches(
|
||||||
|
&opts,
|
||||||
|
true,
|
||||||
|
Some(&f.relay.secret_key().to_secret_hex()),
|
||||||
|
&mut deletion,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(actual.items, expected.items);
|
||||||
|
let after = export(&f.pool).await;
|
||||||
|
for (table, rows) in &before {
|
||||||
|
if ![
|
||||||
|
"events",
|
||||||
|
"users",
|
||||||
|
"nip_fi_profile_heads",
|
||||||
|
"archived_identities",
|
||||||
|
"event_mentions",
|
||||||
|
]
|
||||||
|
.contains(&table.as_str())
|
||||||
|
&& !table.starts_with("events_")
|
||||||
|
{
|
||||||
|
assert_eq!(rows, &after[table], "unexpected change to {table}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let remaining: Vec<Vec<u8>> =
|
||||||
|
sqlx::query_scalar("SELECT pubkey FROM users WHERE community_id=$1")
|
||||||
|
.bind(f.community)
|
||||||
|
.fetch_all(&f.pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(remaining, vec![f.other.public_key().to_bytes().to_vec()]);
|
||||||
|
for (table, old_rows) in &before {
|
||||||
|
for row in old_rows.as_array().unwrap() {
|
||||||
|
let key = row["pubkey"]
|
||||||
|
.as_str()
|
||||||
|
.unwrap_or("")
|
||||||
|
.trim_start_matches("\\x");
|
||||||
|
if row["community_id"] == json!(f.elsewhere) || key == f.other.public_key().to_hex() {
|
||||||
|
assert!(
|
||||||
|
after[table].as_array().unwrap().contains(row),
|
||||||
|
"survivor changed in {table}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let other_count: i64 = sqlx::query_scalar("SELECT count(*) FROM users WHERE community_id=$1")
|
||||||
|
.bind(f.elsewhere)
|
||||||
|
.fetch_one(&f.pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(other_count, 3);
|
||||||
|
let snapshot=sqlx::query("SELECT id,pubkey,extract(epoch FROM created_at)::bigint AS created_at,kind,tags,content,sig FROM events WHERE community_id=$1 AND kind=13535").bind(f.community).fetch_one(&f.pool).await.unwrap();
|
||||||
|
use sqlx::Row;
|
||||||
|
let signed:Event=serde_json::from_value(json!({"id":hex::encode(snapshot.get::<Vec<u8>,_>("id")),"pubkey":hex::encode(snapshot.get::<Vec<u8>,_>("pubkey")),"created_at":snapshot.get::<i64,_>("created_at"),"kind":13535,"tags":snapshot.get::<Value,_>("tags"),"content":snapshot.get::<String,_>("content"),"sig":hex::encode(snapshot.get::<Vec<u8>,_>("sig"))})).unwrap();
|
||||||
|
signed.verify().unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
signed
|
||||||
|
.tags
|
||||||
|
.iter()
|
||||||
|
.filter(|t| t.as_slice().first().map(String::as_str) == Some("p"))
|
||||||
|
.count(),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
assert!(serde_json::to_string(&signed.tags)
|
||||||
|
.unwrap()
|
||||||
|
.contains(&f.other.public_key().to_hex()));
|
||||||
|
assert!(!serde_json::to_string(&signed.tags)
|
||||||
|
.unwrap()
|
||||||
|
.contains(&f.human.public_key().to_hex()));
|
||||||
|
let second = f
|
||||||
|
.store
|
||||||
|
.run_profile_batches(&opts, true, None, &mut Vec::new())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(second.items, 0);
|
||||||
|
assert_eq!(after, export(&f.pool).await);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
#[ignore = "requires Postgres"]
|
||||||
|
async fn limits_dependencies_and_signer_fail_before_any_mutation() {
|
||||||
|
let f = Fixture::new().await;
|
||||||
|
f.profiles().await;
|
||||||
|
let before = export(&f.pool).await;
|
||||||
|
let mut opts = f.options(1);
|
||||||
|
opts.max_items = 1;
|
||||||
|
assert!(f
|
||||||
|
.store
|
||||||
|
.run_profile_batches(&opts, true, None, &mut Vec::new())
|
||||||
|
.await
|
||||||
|
.is_err());
|
||||||
|
opts.max_items = 1000;
|
||||||
|
for key in [None, Some(f.other.secret_key().to_secret_hex())] {
|
||||||
|
assert!(f
|
||||||
|
.store
|
||||||
|
.run_profile_batches(&opts, true, key.as_deref(), &mut Vec::new())
|
||||||
|
.await
|
||||||
|
.is_err());
|
||||||
|
assert_eq!(before, export(&f.pool).await);
|
||||||
|
}
|
||||||
|
opts.relay_pubkeys.clear();
|
||||||
|
assert!(f
|
||||||
|
.store
|
||||||
|
.run_profile_batches(&opts, false, None, &mut Vec::new())
|
||||||
|
.await
|
||||||
|
.is_err());
|
||||||
|
assert_eq!(before, export(&f.pool).await);
|
||||||
|
opts = f.options(1);
|
||||||
|
f.event(
|
||||||
|
f.community,
|
||||||
|
&f.agent,
|
||||||
|
1,
|
||||||
|
vec![],
|
||||||
|
"content must be cleaned first",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let before = export(&f.pool).await;
|
||||||
|
let mut output = Vec::new();
|
||||||
|
assert!(f
|
||||||
|
.store
|
||||||
|
.run_profile_batches(
|
||||||
|
&opts,
|
||||||
|
true,
|
||||||
|
Some(&f.relay.secret_key().to_secret_hex()),
|
||||||
|
&mut output
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.is_err());
|
||||||
|
assert!(String::from_utf8(output)
|
||||||
|
.unwrap()
|
||||||
|
.contains("content/account cleanup"));
|
||||||
|
assert_eq!(before, export(&f.pool).await);
|
||||||
|
}
|
||||||
|
|
||||||
|
struct FailAfterCommit;
|
||||||
|
impl Write for FailAfterCommit {
|
||||||
|
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||||
|
if String::from_utf8_lossy(bytes).contains("batch_committed") {
|
||||||
|
Err(std::io::Error::other("injected output loss"))
|
||||||
|
} else {
|
||||||
|
Ok(bytes.len())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn flush(&mut self) -> std::io::Result<()> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[tokio::test]
|
||||||
|
#[ignore = "requires Postgres"]
|
||||||
|
async fn commit_before_output_loss_resumes_from_same_target_scope() {
|
||||||
|
let f = Fixture::new().await;
|
||||||
|
f.profiles().await;
|
||||||
|
let opts = f.options(2);
|
||||||
|
assert!(f
|
||||||
|
.store
|
||||||
|
.run_profile_batches(
|
||||||
|
&opts,
|
||||||
|
true,
|
||||||
|
Some(&f.relay.secret_key().to_secret_hex()),
|
||||||
|
&mut FailAfterCommit
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.is_err());
|
||||||
|
let mut output = Vec::new();
|
||||||
|
f.store
|
||||||
|
.run_profile_batches(
|
||||||
|
&opts,
|
||||||
|
true,
|
||||||
|
Some(&f.relay.secret_key().to_secret_hex()),
|
||||||
|
&mut output,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(String::from_utf8(output)
|
||||||
|
.unwrap()
|
||||||
|
.contains("delete_complete"));
|
||||||
|
assert_eq!(
|
||||||
|
f.store
|
||||||
|
.run_profile_batches(&opts, true, None, &mut Vec::new())
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.items,
|
||||||
|
0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
#[ignore = "requires Postgres"]
|
||||||
|
async fn changed_source_rolls_back_batch_and_changed_owner_is_refused() {
|
||||||
|
let f = Fixture::new().await;
|
||||||
|
f.event(f.community, &f.human, 0, vec![], "initial").await;
|
||||||
|
let mut conn = f.pool.acquire().await.unwrap();
|
||||||
|
let plan = plan::build(&mut conn, &f.options(100)).await.unwrap();
|
||||||
|
sqlx::query("UPDATE events SET content='changed' WHERE community_id=$1")
|
||||||
|
.bind(f.community)
|
||||||
|
.execute(&f.pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let mut raw = f.pool.begin().await.unwrap();
|
||||||
|
lock(&mut raw, &plan.scope).await.unwrap();
|
||||||
|
let mut tx = crate::AdmittedTx::admit(
|
||||||
|
raw,
|
||||||
|
&crate::deletion::DeletionStore::new(f.pool.clone()),
|
||||||
|
buzz_core::CommunityId::from_uuid(f.community),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
rows::apply(&mut tx, &plan.scope, &plan.ops[0], &Default::default())
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
tx.rollback().await.unwrap();
|
||||||
|
let before = export(&f.pool).await;
|
||||||
|
sqlx::query("UPDATE users SET agent_owner_pubkey=$2 WHERE community_id=$1 AND pubkey=$3")
|
||||||
|
.bind(f.community)
|
||||||
|
.bind(f.other.public_key().to_bytes().as_slice())
|
||||||
|
.bind(f.agent.public_key().to_bytes().as_slice())
|
||||||
|
.execute(&f.pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(f
|
||||||
|
.store
|
||||||
|
.run_profile_batches(&f.options(100), true, None, &mut Vec::new())
|
||||||
|
.await
|
||||||
|
.is_err());
|
||||||
|
assert_eq!(before["events"], export(&f.pool).await["events"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
#[ignore = "requires Postgres"]
|
||||||
|
async fn mismatched_verified_subject_and_survivor_archive_actor_are_not_erased() {
|
||||||
|
let f = Fixture::new().await;
|
||||||
|
f.event(
|
||||||
|
f.community,
|
||||||
|
&f.relay,
|
||||||
|
30382,
|
||||||
|
vec![
|
||||||
|
vec!["p".into(), f.human.public_key().to_hex()],
|
||||||
|
vec!["d".into(), f.other.public_key().to_hex()],
|
||||||
|
],
|
||||||
|
"",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let before = export(&f.pool).await;
|
||||||
|
assert!(f
|
||||||
|
.store
|
||||||
|
.run_profile_batches(&f.options(100), true, None, &mut Vec::new())
|
||||||
|
.await
|
||||||
|
.is_err());
|
||||||
|
assert_eq!(before, export(&f.pool).await);
|
||||||
|
}
|
||||||
156
crates/buzz-db/src/store/user_deletion/profile_batches/rows.rs
Normal file
156
crates/buzz-db/src/store/user_deletion/profile_batches/rows.rs
Normal file
@@ -0,0 +1,156 @@
|
|||||||
|
use super::*;
|
||||||
|
use sqlx::Row;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
pub(super) struct Table {
|
||||||
|
pub name: &'static str,
|
||||||
|
key: &'static str,
|
||||||
|
identity: &'static str,
|
||||||
|
pub selector: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) struct Operation {
|
||||||
|
pub table: &'static Table,
|
||||||
|
pub key: Value,
|
||||||
|
pub fingerprint: String,
|
||||||
|
pub snapshot: Option<events::Snapshot>,
|
||||||
|
}
|
||||||
|
impl Operation {
|
||||||
|
pub fn cost(&self) -> usize {
|
||||||
|
if self.snapshot.is_some() {
|
||||||
|
2
|
||||||
|
} else {
|
||||||
|
1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn description(&self) -> Value {
|
||||||
|
json!({"table":self.table.name,"key":self.key,
|
||||||
|
"action":if self.snapshot.is_some() {"replace_archive_snapshot"} else {"delete"}})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) const EVENTS: Table = Table {
|
||||||
|
name: "events",
|
||||||
|
key: "jsonb_build_object('id',t.id,'created_at',t.created_at)",
|
||||||
|
identity: "id=($2->>'id')::bytea AND created_at=($2->>'created_at')::timestamptz",
|
||||||
|
selector: "t.id=ANY($3::bytea[])",
|
||||||
|
};
|
||||||
|
pub(super) const HEADS: Table = Table {
|
||||||
|
name: "nip_fi_profile_heads",
|
||||||
|
key: "jsonb_build_object('pubkey',t.pubkey)",
|
||||||
|
identity: "pubkey=$2->>'pubkey'",
|
||||||
|
selector: "t.pubkey=ANY(SELECT encode(k,'hex') FROM unnest($2::bytea[]) k)",
|
||||||
|
};
|
||||||
|
pub(super) const ARCHIVES: Table = Table {
|
||||||
|
name: "archived_identities",
|
||||||
|
key: "jsonb_build_object('pubkey',t.pubkey)",
|
||||||
|
identity: "pubkey=$2->>'pubkey'",
|
||||||
|
selector: HEADS.selector,
|
||||||
|
};
|
||||||
|
pub(super) const USERS: Table = Table {
|
||||||
|
name: "users",
|
||||||
|
key: "jsonb_build_object('pubkey',t.pubkey)",
|
||||||
|
identity: "pubkey=($2->>'pubkey')::bytea",
|
||||||
|
selector: "t.pubkey=ANY($2::bytea[])",
|
||||||
|
};
|
||||||
|
|
||||||
|
pub(super) const CHILDREN: &[Table] = &[
|
||||||
|
Table { name:"event_mentions", key:"jsonb_build_object('pubkey_hex',t.pubkey_hex,'event_id',t.event_id)",
|
||||||
|
identity:"pubkey_hex=$2->>'pubkey_hex' AND event_id=($2->>'event_id')::bytea", selector:"t.event_id=ANY($3::bytea[])" },
|
||||||
|
Table { name:"reactions", key:"jsonb_build_object('event_created_at',t.event_created_at,'event_id',t.event_id,'pubkey',t.pubkey,'emoji',t.emoji)",
|
||||||
|
identity:"event_created_at=($2->>'event_created_at')::timestamptz AND event_id=($2->>'event_id')::bytea AND pubkey=($2->>'pubkey')::bytea AND emoji=$2->>'emoji'",
|
||||||
|
selector:"t.event_id=ANY($3::bytea[]) OR t.reaction_event_id=ANY($3::bytea[])" },
|
||||||
|
Table { name:"push_match_queue", key:"jsonb_build_object('event_id',t.event_id)", identity:"event_id=($2->>'event_id')::bytea", selector:"t.event_id=ANY($3::bytea[])" },
|
||||||
|
Table { name:"push_wake_outbox", key:"jsonb_build_object('id',t.id)", identity:"id=($2->>'id')::uuid", selector:"t.event_id=ANY($3::bytea[])" },
|
||||||
|
Table { name:"operator_listener_outbox", key:"jsonb_build_object('id',t.id)", identity:"id=($2->>'id')::uuid", selector:"t.event_id=ANY($3::bytea[])" },
|
||||||
|
Table { name:"delivery_log", key:"jsonb_build_object('id',t.id,'delivered_at',t.delivered_at)", identity:"id=($2->>'id')::bigint AND delivered_at=($2->>'delivered_at')::timestamptz", selector:"t.event_id=ANY($3::bytea[])" },
|
||||||
|
];
|
||||||
|
|
||||||
|
pub(super) async fn collect(
|
||||||
|
conn: &mut PgConnection,
|
||||||
|
plan: &mut Plan,
|
||||||
|
table: &'static Table,
|
||||||
|
ids: &[Vec<u8>],
|
||||||
|
max: u32,
|
||||||
|
) -> Result<()> {
|
||||||
|
let sql = format!("SELECT {} AS key, encode(sha256(convert_to(to_jsonb(t)::text,'UTF8')),'hex') AS fingerprint FROM {} t \
|
||||||
|
WHERE community_id=$1 AND ({}) AND cardinality($2::bytea[])>=0 AND cardinality($3::bytea[])>=0 \
|
||||||
|
ORDER BY {} LIMIT $4", table.key, table.name, table.selector, table.key);
|
||||||
|
let rows = sqlx::query(sqlx::AssertSqlSafe(sql))
|
||||||
|
.bind(plan.scope.community)
|
||||||
|
.bind(&plan.scope.bytes)
|
||||||
|
.bind(ids)
|
||||||
|
.bind((i64::from(max).saturating_sub(plan.ops.len() as i64) + 1).min(65_537))
|
||||||
|
.fetch_all(conn)
|
||||||
|
.await?;
|
||||||
|
for row in rows {
|
||||||
|
push(
|
||||||
|
plan,
|
||||||
|
Operation {
|
||||||
|
table,
|
||||||
|
key: row.try_get("key")?,
|
||||||
|
fingerprint: row.try_get("fingerprint")?,
|
||||||
|
snapshot: None,
|
||||||
|
},
|
||||||
|
max,
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn push(plan: &mut Plan, op: Operation, max: u32) -> Result<()> {
|
||||||
|
if plan.ops.len() >= 65_536 {
|
||||||
|
return Err(invalid(
|
||||||
|
"profile plan exceeds 65536-operation memory budget; no deletion performed",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if plan.ops.len() >= max as usize {
|
||||||
|
return Err(invalid(
|
||||||
|
"profile plan exceeds max-items; no deletion performed",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
// Keys are bounded; the full source payload never enters the plan or output.
|
||||||
|
if serde_json::to_vec(&op.key)?.len() > 1024 {
|
||||||
|
return Err(invalid("oversized profile row key"));
|
||||||
|
}
|
||||||
|
plan.ops.push(op);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn apply(
|
||||||
|
tx: &mut crate::AdmittedTx,
|
||||||
|
scope: &Scope,
|
||||||
|
op: &Operation,
|
||||||
|
replacements: &HashMap<String, nostr::Event>,
|
||||||
|
) -> Result<()> {
|
||||||
|
if op.table.name == "users" {
|
||||||
|
let blockers = plan::dependencies(tx.conn(), scope).await?;
|
||||||
|
if !blockers.is_empty() {
|
||||||
|
return Err(invalid(format!(
|
||||||
|
"identity removal blocked: {}",
|
||||||
|
blockers.join(", ")
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let changed = if op.snapshot.is_some() {
|
||||||
|
events::replace_snapshot(tx, scope, op, replacements).await?
|
||||||
|
} else {
|
||||||
|
let sql = format!(
|
||||||
|
"DELETE FROM {} t WHERE community_id=$1 AND ({}) AND encode(sha256(convert_to(to_jsonb(t)::text,'UTF8')),'hex')=$3",
|
||||||
|
op.table.name, op.table.identity
|
||||||
|
);
|
||||||
|
sqlx::query(sqlx::AssertSqlSafe(sql))
|
||||||
|
.bind(scope.community)
|
||||||
|
.bind(&op.key)
|
||||||
|
.bind(&op.fingerprint)
|
||||||
|
.execute(tx.conn())
|
||||||
|
.await?
|
||||||
|
.rows_affected()
|
||||||
|
};
|
||||||
|
if changed != 1 {
|
||||||
|
return Err(invalid(
|
||||||
|
"selected profile row changed; current batch rolled back; re-preview",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -7,6 +7,8 @@ use uuid::Uuid;
|
|||||||
/// Preview real memberships or prepare and execute synthetic deletion requests.
|
/// Preview real memberships or prepare and execute synthetic deletion requests.
|
||||||
#[derive(Debug, Subcommand)]
|
#[derive(Debug, Subcommand)]
|
||||||
pub enum Command {
|
pub enum Command {
|
||||||
|
/// Preview or delete profiles in one community; deletion requires stopped writers.
|
||||||
|
ProfileBatches(profile_batches::Args),
|
||||||
/// Print real current memberships as JSON; does not save or execute a request.
|
/// Print real current memberships as JSON; does not save or execute a request.
|
||||||
Inventory {
|
Inventory {
|
||||||
/// Demo fixture (default), hex public key, or npub. Current memberships only.
|
/// Demo fixture (default), hex public key, or npub. Current memberships only.
|
||||||
@@ -74,6 +76,10 @@ pub enum Command {
|
|||||||
|
|
||||||
/// Run inventory discovery or synthetic workflow commands against PostgreSQL.
|
/// Run inventory discovery or synthetic workflow commands against PostgreSQL.
|
||||||
pub async fn run(command: Command) -> Result<i32> {
|
pub async fn run(command: Command) -> Result<i32> {
|
||||||
|
let command = match command {
|
||||||
|
Command::ProfileBatches(args) => return profile_batches::run(args).await,
|
||||||
|
other => other,
|
||||||
|
};
|
||||||
let db = if matches!(command, Command::Inventory { .. }) {
|
let db = if matches!(command, Command::Inventory { .. }) {
|
||||||
buzz_db::Db::connect_cold_start(
|
buzz_db::Db::connect_cold_start(
|
||||||
buzz_db::DbConfig {
|
buzz_db::DbConfig {
|
||||||
@@ -91,6 +97,7 @@ pub async fn run(command: Command) -> Result<i32> {
|
|||||||
};
|
};
|
||||||
let store = db.entity_deletion_store();
|
let store = db.entity_deletion_store();
|
||||||
match command {
|
match command {
|
||||||
|
Command::ProfileBatches(_) => anyhow::bail!("profile command was not dispatched"),
|
||||||
Command::Inventory { pubkey } => {
|
Command::Inventory { pubkey } => {
|
||||||
crate::print_json(&inventory::generate(&db, &pubkey).await?)?;
|
crate::print_json(&inventory::generate(&db, &pubkey).await?)?;
|
||||||
}
|
}
|
||||||
@@ -154,6 +161,7 @@ mod handlers;
|
|||||||
mod inventory;
|
mod inventory;
|
||||||
/// Standalone delegation of an owned community to community deletion.
|
/// Standalone delegation of an owned community to community deletion.
|
||||||
pub mod owned_community;
|
pub mod owned_community;
|
||||||
|
mod profile_batches;
|
||||||
/// Read-only summaries of locally saved request progress and external waits.
|
/// Read-only summaries of locally saved request progress and external waits.
|
||||||
pub mod summary;
|
pub mod summary;
|
||||||
mod transition;
|
mod transition;
|
||||||
|
|||||||
120
crates/buzz-deletion/src/user/profile_batches.rs
Normal file
120
crates/buzz-deletion/src/user/profile_batches.rs
Normal file
@@ -0,0 +1,120 @@
|
|||||||
|
//! Standalone profile command. No workflow stages are enabled here.
|
||||||
|
use anyhow::Result;
|
||||||
|
use buzz_db::user_deletion::profile_batches::ProfileBatchOptions;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
/// Scope and limits for offline profile cleanup.
|
||||||
|
#[derive(Debug, clap::Args)]
|
||||||
|
pub struct Args {
|
||||||
|
/// Human public key (hex or npub); includes directly owned agents.
|
||||||
|
#[arg(long, value_parser = parse_key)]
|
||||||
|
pubkey: String,
|
||||||
|
/// One explicit surviving community, including former memberships.
|
||||||
|
#[arg(long)]
|
||||||
|
community: Uuid,
|
||||||
|
/// Saved agent key for retry after its identity row disappeared; repeatable.
|
||||||
|
#[arg(long, value_parser = parse_key)]
|
||||||
|
agent_pubkey: Vec<String>,
|
||||||
|
/// Trusted relay signer for verified profiles and archive events; repeatable.
|
||||||
|
#[arg(long, value_parser = parse_key)]
|
||||||
|
relay_pubkey: Vec<String>,
|
||||||
|
/// Print proposed rows without writing anything (the default).
|
||||||
|
#[arg(long, alias = "read-only", conflicts_with = "delete")]
|
||||||
|
print_only: bool,
|
||||||
|
/// Apply batches. Stop relay and external writers; finish content/account/media cleanup first.
|
||||||
|
#[arg(long, conflicts_with = "print_only")]
|
||||||
|
delete: bool,
|
||||||
|
/// Maximum row mutations per transaction, 1–100.
|
||||||
|
#[arg(long, default_value_t = 100, value_parser = clap::value_parser!(u16).range(1..=100))]
|
||||||
|
batch_size: u16,
|
||||||
|
/// Maximum planned row mutations; exceeding the limit fails before deletion.
|
||||||
|
#[arg(long, default_value_t = 100_000, value_parser = clap::value_parser!(u32).range(1..=1_000_000))]
|
||||||
|
max_items: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_key(value: &str) -> std::result::Result<String, String> {
|
||||||
|
buzz_db::user_deletion::normalize_user_deletion_pubkey(value).map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn run(args: Args) -> Result<i32> {
|
||||||
|
let db = buzz_db::Db::connect_cold_start(
|
||||||
|
buzz_db::DbConfig {
|
||||||
|
database_url: crate::required_env("DATABASE_URL")?,
|
||||||
|
max_connections: 1,
|
||||||
|
min_connections: 0,
|
||||||
|
default_transaction_read_only: !args.delete,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
"profile_batches",
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
// Never parse, require or print a private key during preview.
|
||||||
|
let secret = if args.delete {
|
||||||
|
std::env::var("BUZZ_RELAY_PRIVATE_KEY").ok()
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
db.user_deletion_store()
|
||||||
|
.run_profile_batches(
|
||||||
|
&ProfileBatchOptions {
|
||||||
|
community: args.community,
|
||||||
|
pubkey: args.pubkey,
|
||||||
|
agent_pubkeys: args.agent_pubkey,
|
||||||
|
relay_pubkeys: args.relay_pubkey,
|
||||||
|
batch_size: args.batch_size,
|
||||||
|
max_items: args.max_items,
|
||||||
|
},
|
||||||
|
args.delete,
|
||||||
|
secret.as_deref(),
|
||||||
|
&mut std::io::stdout(),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
Ok(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use clap::Parser;
|
||||||
|
#[derive(Parser)]
|
||||||
|
struct Cli {
|
||||||
|
#[command(flatten)]
|
||||||
|
args: Args,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn preview_is_default_and_delete_is_explicit() {
|
||||||
|
let base = [
|
||||||
|
"profile-batches",
|
||||||
|
"--pubkey",
|
||||||
|
"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
|
||||||
|
"--community",
|
||||||
|
"00000000-0000-0000-0000-000000000001",
|
||||||
|
];
|
||||||
|
for flag in [None, Some("--print-only"), Some("--read-only")] {
|
||||||
|
assert!(
|
||||||
|
!Cli::try_parse_from(base.into_iter().chain(flag))
|
||||||
|
.unwrap()
|
||||||
|
.args
|
||||||
|
.delete
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
Cli::try_parse_from(base.into_iter().chain(["--delete"]))
|
||||||
|
.unwrap()
|
||||||
|
.args
|
||||||
|
.delete
|
||||||
|
);
|
||||||
|
for flag in ["--print-only", "--read-only"] {
|
||||||
|
assert!(Cli::try_parse_from(base.into_iter().chain([flag, "--delete"])).is_err());
|
||||||
|
}
|
||||||
|
for extra in [
|
||||||
|
["--batch-size", "0"],
|
||||||
|
["--batch-size", "101"],
|
||||||
|
["--max-items", "0"],
|
||||||
|
["--pubkey", "bad"],
|
||||||
|
] {
|
||||||
|
assert!(Cli::try_parse_from(base.into_iter().chain(extra)).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
99
docs/profile-cleanup.md
Normal file
99
docs/profile-cleanup.md
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
# Standalone profile cleanup
|
||||||
|
|
||||||
|
`buzz-admin user-deletions profile-batches` previews or removes profile data in
|
||||||
|
one explicit community. This is the identity step after content, account and
|
||||||
|
media cleanup. It does not enable the user-deletion workflow or declare complete
|
||||||
|
account erasure.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# DATABASE_URL selects the operator database. Preview is the default.
|
||||||
|
buzz-admin user-deletions profile-batches \
|
||||||
|
--pubkey <human-hex-or-npub> --community <uuid> --print-only
|
||||||
|
|
||||||
|
# --read-only is an alias for --print-only.
|
||||||
|
# Stop the relay and external writers and finish earlier cleanup first.
|
||||||
|
buzz-admin user-deletions profile-batches \
|
||||||
|
--pubkey <human-hex-or-npub> --community <uuid> --delete
|
||||||
|
```
|
||||||
|
|
||||||
|
The human and directly owned agent keys are resolved through `users`, including
|
||||||
|
ownership found in other communities. Every mutation is limited to `--community`.
|
||||||
|
A local agent row owned by someone else, a changed owner, or an unselected child
|
||||||
|
agent blocks execution. The output prints the complete `target_pubkeys`. Save it;
|
||||||
|
repeat `--agent-pubkey <key>` for those agents on retries after identity rows have
|
||||||
|
been removed. Explicit agent keys are operator-supplied saved scope, not evidence
|
||||||
|
of authorization. This command requires privileged database access.
|
||||||
|
|
||||||
|
The supported families are ordinary profiles (0/10100), owner-authored managed
|
||||||
|
agent records (30177/30179), verified profiles (30382), archive requests and
|
||||||
|
deltas (9035/9036/8002/8003), archive snapshots (13535), `nip_fi_profile_heads`,
|
||||||
|
`archived_identities`, and final `users` rows. Event-dependent mention, reaction
|
||||||
|
and delivery projections are removed before their source events. Agent identity
|
||||||
|
rows go before the human row. Reserved kind 30179 is cleaned only if stored;
|
||||||
|
this command does not enable its ingestion or decrypt its payload.
|
||||||
|
|
||||||
|
Verified profiles are selected by their matching `d`/`p` subject, not the event
|
||||||
|
author. Supply `--relay-pubkey <hex-or-npub>` for each independently verified
|
||||||
|
relay signer. A missing or untrusted signer stops the operation. The same trust
|
||||||
|
rule applies to archive deltas and snapshots. Human-signed requests about another
|
||||||
|
identity and archive actor/replacement references on surviving identities need
|
||||||
|
an explicit shared-history disposition; the command reports them as blockers.
|
||||||
|
|
||||||
|
Shared archive snapshots are rebuilt from the retained canonical archive rows.
|
||||||
|
The snapshot replacement is a fresh signed event; no old signature is reused.
|
||||||
|
Deletion requires `BUZZ_RELAY_PRIVATE_KEY` matching the affected snapshot signer.
|
||||||
|
Preview never requires or reads this key. Historical snapshots that require a
|
||||||
|
different signing key remain blocked pending reconciliation. Do not pass secrets
|
||||||
|
on the command line or include them in logs.
|
||||||
|
|
||||||
|
Each JSON line describes the scope, proposed batch, committed batch, or final
|
||||||
|
summary. Batches default to 100 row mutations; `--batch-size` accepts 1–100.
|
||||||
|
Replacing a snapshot costs two mutations (delete and insert in one transaction),
|
||||||
|
so it requires a batch size of at least two. `--max-items` defaults to 100,000;
|
||||||
|
exceeding it fails before deletion. Additional memory limits cap a plan at 65,536
|
||||||
|
operations and candidate tags at 32 MiB (64 KiB per event); archive snapshots
|
||||||
|
support up to 10,000 retained identities. Exceeding any limit is an error, never
|
||||||
|
a successful partial preview. SQL statements have a 30-second timeout and locks
|
||||||
|
a three-second timeout; large accounts can require a separately reviewed plan.
|
||||||
|
|
||||||
|
Before mutations, the command rejects remaining credentials, memberships,
|
||||||
|
workflows, subscriptions, non-profile authored content and unresolved archive
|
||||||
|
references. It retains replay watermarks, deletion fences, requests, approvals,
|
||||||
|
history, repositories and media objects. Media cleanup must preserve its source
|
||||||
|
evidence before this command removes avatar/configuration references.
|
||||||
|
|
||||||
|
Each committed batch survives interruption. Rerun with the saved target keys to
|
||||||
|
plan the remaining rows. Source fingerprints and ownership are rechecked inside
|
||||||
|
the batch transaction; a mismatch rolls back that batch. A failure after commit
|
||||||
|
but before output is an error and does not mean the batch rolled back. No success
|
||||||
|
marker is printed if prerequisites or final profile checks fail. The final
|
||||||
|
summary always has `account_erasure_complete: false`.
|
||||||
|
|
||||||
|
The stopped-writer requirement includes pending login-triggered verified-profile
|
||||||
|
publication and external agent/config writers. This command does not add online
|
||||||
|
admission fencing or invalidate client caches. Restart/refresh the supported
|
||||||
|
serving processes and clients as part of the full deletion procedure. Retaining
|
||||||
|
replay records alone does not prove every writer is fenced. Ordinary verified
|
||||||
|
profiles remain historical records; explicit operator erasure is a separate
|
||||||
|
exception to normal refresh behavior.
|
||||||
|
|
||||||
|
## Local verification
|
||||||
|
|
||||||
|
Use a disposable database and relay, following `TESTING.md`; do not reuse a
|
||||||
|
Desktop database. Seed a human, two owned agents, a survivor, and a second
|
||||||
|
community. Include ordinary/verified profiles, managed configuration and a
|
||||||
|
shared archive snapshot. Complete content/account cleanup in the first community.
|
||||||
|
|
||||||
|
1. Export every table and the object inventory. Run print-only with the known
|
||||||
|
relay public key. Compare every selected key with the expected inventory and
|
||||||
|
confirm all exports are unchanged.
|
||||||
|
2. Stop writers. Run delete with the same scope and relay signing key. Compare
|
||||||
|
proposed and committed keys and the surviving data, including the second
|
||||||
|
community. Verify the new shared snapshot signature and survivor list.
|
||||||
|
3. Rerun with the saved agent keys; expect zero operations. Interrupt a multi-batch
|
||||||
|
run and repeat to confirm recovery. Introduce an unresolved dependency or a
|
||||||
|
wrong signer and confirm no deletion occurs.
|
||||||
|
4. Restart the isolated relay and reload clients. Check profile-event queries,
|
||||||
|
directory/name search and NIP-05. Test old-event replay and fresh admission
|
||||||
|
under the full deletion procedure's write restrictions. Report any recreation;
|
||||||
|
the standalone database result does not certify online enforcement.
|
||||||
Reference in New Issue
Block a user