diff --git a/Justfile b/Justfile index 7281f69788..3d9fb7ab92 100644 --- a/Justfile +++ b/Justfile @@ -436,6 +436,9 @@ test-unit: # buzz-workflow parser, cron, condition and denial-logging unit tests # (infra-free). Its ignored Postgres cases run in the PostgreSQL lane. cargo nextest run -p buzz-workflow --lib + # Deletion workflow/unit tests; Postgres cases remain ignored here. + # Keep the Cargo fallback in scripts/run-tests.sh in step. + cargo nextest run -p buzz-deletion --lib # buzz-acp owns the relay-to-agent trust boundary. Run its tests here so # forged relay events cannot regain a path into agent routing unnoticed. cargo nextest run -p buzz-acp diff --git a/crates/buzz-admin/src/main.rs b/crates/buzz-admin/src/main.rs index 86551425fa..7fe7c0554b 100644 --- a/crates/buzz-admin/src/main.rs +++ b/crates/buzz-admin/src/main.rs @@ -730,7 +730,6 @@ async fn reconcile_channels( channel_arg: Option, relay_key_arg: Option, ) -> Result<()> { - use buzz_core::channel::group_state_identity_tags; use buzz_core::kind::KIND_NIP29_GROUP_ADMINS; use buzz_db::event::EventQuery; @@ -829,19 +828,11 @@ async fn reconcile_channels( // kind:39001 — admins { - let mut tags: Vec = vec![Tag::parse(["d", &channel_id_str])?]; - tags.extend(group_state_identity_tags( - &channel.channel_type, - &channel.labels, - &channel.created_by, - )?); - for m in members - .iter() - .filter(|m| m.role == "owner" || m.role == "admin") - { - let pk = hex::encode(&m.pubkey); - tags.push(Tag::parse(["p", &pk, &m.role])?); - } + let tags = buzz_db::channel::group_admins_tags( + &channel_id_str, + &channel.identity(), + &members, + )?; let event = EventBuilder::new(Kind::Custom(KIND_NIP29_GROUP_ADMINS as u16), "") .tags(tags) .sign_with_keys(&relay_keys) @@ -853,16 +844,11 @@ async fn reconcile_channels( // kind:39002 — members { - let mut tags: Vec = vec![Tag::parse(["d", &channel_id_str])?]; - tags.extend(group_state_identity_tags( - &channel.channel_type, - &channel.labels, - &channel.created_by, - )?); - for m in &members { - let pk = hex::encode(&m.pubkey); - tags.push(Tag::parse(["p", &pk, "", &m.role])?); - } + let tags = buzz_db::channel::group_members_tags( + &channel_id_str, + Some(&channel.identity()), + &members, + )?; let event = EventBuilder::new(Kind::Custom(39002), "") .tags(tags) .sign_with_keys(&relay_keys) diff --git a/crates/buzz-admin/tests/postgres_account_output.rs b/crates/buzz-admin/tests/postgres_account_output.rs new file mode 100644 index 0000000000..3f2df91db3 --- /dev/null +++ b/crates/buzz-admin/tests/postgres_account_output.rs @@ -0,0 +1,210 @@ +//! The workflow emits one JSON document; direct account cleanup emits NDJSON. +use buzz_db::entity_deletion::{NewEntityStage, NextStage, StageTransition}; +use buzz_db::user_deletion::UserDeletionInventory; +use buzz_db::Db; +use serde_json::{json, Value}; +use sqlx::PgPool; +use std::process::Output; +use std::time::Duration; +use tokio::process::Command; +use uuid::Uuid; + +const TARGET: &str = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; + +async fn cli(url: &str, args: &[&str]) -> Output { + let binary = std::env::var_os("NEXTEST_BIN_EXE_buzz_admin") + .unwrap_or_else(|| env!("CARGO_BIN_EXE_buzz-admin").into()); + let output = tokio::time::timeout( + Duration::from_secs(20), + Command::new(binary) + .arg("user-deletions") + .args(args) + .env("DATABASE_URL", url) + .env("BUZZ_DB_POOL_SIZE", "2") + .env("BUZZ_RELAY_PRIVATE_KEY", format!("{:064x}", 1)) + .env_remove("RELAY_OPERATOR_PUBKEYS") + .env_remove("RELAY_OWNER_PUBKEY") + .kill_on_drop(true) + .output(), + ) + .await + .unwrap() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + output +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn account_workflow_stdout_is_one_document_and_direct_output_remains_ndjson() { + let url = std::env::var("BUZZ_TEST_DATABASE_URL") + .or_else(|_| std::env::var("DATABASE_URL")) + .unwrap(); + let pool = PgPool::connect(&url).await.unwrap(); + let db = Db::from_pool(pool.clone()); + if std::env::var("BUZZ_TEST_SCHEMA_MODE").as_deref() != Ok("desired") { + db.migrate().await.unwrap(); + } + let community = Uuid::new_v4(); + sqlx::query("INSERT INTO communities(id,host) VALUES ($1,$2)") + .bind(community) + .bind(format!("{community}.example.org")) + .execute(&pool) + .await + .unwrap(); + sqlx::query("INSERT INTO users(community_id,pubkey) VALUES ($1,decode($2,'hex'))") + .bind(community) + .bind(TARGET) + .execute(&pool) + .await + .unwrap(); + sqlx::query("INSERT INTO relay_members(community_id,pubkey,role) VALUES ($1,$2,'member')") + .bind(community) + .bind(TARGET) + .execute(&pool) + .await + .unwrap(); + let request = db + .user_deletion_store() + .submit(TARGET, "fixture", None) + .await + .unwrap(); + let store = db.entity_deletion_store(); + store + .approve( + request.id, + "fixture", + request.inventory_digest.as_deref().unwrap(), + ) + .await + .unwrap(); + let lease = store + .claim(request.id, "fixture", Duration::from_secs(60)) + .await + .unwrap() + .unwrap(); + let inventory = UserDeletionInventory::read(&request).unwrap(); + let mut previous = None; + // Gate/media are fixture preconditions. Content and account execution, + // transitions, roster signing, stdout and lease release use production code. + for (name, scope, decision) in [ + ("gate_user", None, Value::Null), + ( + "purge_media", + None, + json!({"kind":"stage","stage":"purge_media"}), + ), + ( + "purge_content", + Some(community), + json!({"kind":"enter_communities"}), + ), + ] { + let next = NewEntityStage { + stage: name.into(), + community: scope, + inputs: inventory.inputs(TARGET, scope).unwrap(), + }; + let result = store + .transition_stage(&lease, previous, |_, _| { + Ok(match previous { + None => StageTransition::Initialize(next), + Some(id) => StageTransition::Advance { + previous: id, + decision, + successor: Some(next), + }, + }) + }) + .await + .unwrap(); + let NextStage::Stage(stage) = result else { + panic!("expected stage"); + }; + if name != "purge_content" { + store.start_stage(&lease, stage.id).await.unwrap(); + store + .save_stage_success(&lease, stage.id, json!({"fixture":true})) + .await + .unwrap(); + } + previous = Some(stage.id); + } + store.release(&lease).await.unwrap(); + let community_text = community.to_string(); + let direct = cli( + &url, + &[ + "account-batches", + "--pubkey", + TARGET, + "--community", + &community_text, + ], + ) + .await; + let records: Vec = String::from_utf8(direct.stdout) + .unwrap() + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect(); + assert!(records + .iter() + .any(|r| r["record"] == "proposed_batch" && r["table"] == "relay_members")); + let content = cli( + &url, + &["run", &request.id.to_string(), "--delete", "--next-step"], + ) + .await; + let content_document: Value = serde_json::from_slice(&content.stdout).unwrap(); + let stages = content_document["stage_history"].as_array().unwrap(); + assert!(stages + .iter() + .any(|s| s["stage"] == "purge_content" && s["status"] == "completed")); + assert!(stages.iter().any(|s| s["stage"] == "purge_account" + && s["status"] == "pending" + && s["is_current"] == true)); + let output = cli( + &url, + &["run", &request.id.to_string(), "--delete", "--next-step"], + ) + .await; + let document: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(document["execution"]["lease_owner"], Value::Null); + assert!(document["stage_history"] + .as_array() + .unwrap() + .iter() + .any(|s| s["stage"] == "purge_account" && s["status"] == "completed")); + let progress: Vec = String::from_utf8(output.stderr) + .unwrap() + .lines() + .filter_map(|line| serde_json::from_str(line).ok()) + .collect(); + assert!(progress.iter().any(|r| r["saved_community_roster"] == true)); + let remaining: i64 = sqlx::query_scalar( + "SELECT count(*) FROM relay_members WHERE community_id=$1 AND pubkey=$2", + ) + .bind(community) + .bind(TARGET) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(remaining, 0); + let tags: Value = sqlx::query_scalar( + "SELECT tags FROM events WHERE community_id=$1 AND kind=13534 AND deleted_at IS NULL", + ) + .bind(community) + .fetch_one(&pool) + .await + .unwrap(); + assert!(!tags + .as_array() + .unwrap() + .iter() + .any(|t| t[0] == "member" && t[1] == TARGET)); +} diff --git a/crates/buzz-admin/tests/postgres_user_account_batches.rs b/crates/buzz-admin/tests/postgres_user_account_batches.rs new file mode 100644 index 0000000000..26f406709b --- /dev/null +++ b/crates/buzz-admin/tests/postgres_user_account_batches.rs @@ -0,0 +1,270 @@ +//! Real command wiring: modes, bounded exit status, and resumption. +use nostr::ToBech32; +use serde_json::Value; +use sqlx::PgPool; +use std::time::Duration; +use tokio::process::Command; +use uuid::Uuid; + +const TARGET: &str = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; + +async fn cli(url: &str, community: Uuid, pubkey: &str, args: &[&str], code: i32) -> Vec { + let binary = std::env::var_os("NEXTEST_BIN_EXE_buzz_admin") + .unwrap_or_else(|| env!("CARGO_BIN_EXE_buzz-admin").into()); + let output = tokio::time::timeout( + Duration::from_secs(20), + Command::new(binary) + .args([ + "user-deletions", + "account-batches", + "--community", + &community.to_string(), + "--pubkey", + pubkey, + "--batch-size", + "2", + ]) + .args(args) + .env("DATABASE_URL", url) + .env("BUZZ_AUTO_MIGRATE", "false") + .env("BUZZ_RELAY_PRIVATE_KEY", format!("{:064x}", 1)) + .kill_on_drop(true) + .output(), + ) + .await + .unwrap() + .unwrap(); + assert_eq!( + output.status.code(), + Some(code), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout) + .unwrap() + .lines() + .map(|s| serde_json::from_str(s).unwrap()) + .collect() +} + +async fn tokens(pool: &PgPool) -> Value { + sqlx::query_scalar("SELECT jsonb_agg(to_jsonb(t) ORDER BY community_id,id) FROM api_tokens t") + .fetch_one(pool) + .await + .unwrap() +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn account_command_modes_cap_and_resume_use_real_database_engine() { + let url = std::env::var("BUZZ_TEST_DATABASE_URL") + .or_else(|_| std::env::var("DATABASE_URL")) + .unwrap(); + let pool = PgPool::connect(&url).await.unwrap(); + let community = Uuid::new_v4(); + let other = Uuid::new_v4(); + let seed = include_str!("../../buzz-db/src/store/user_deletion/account_batches/fixture.sql") + .replace("__TARGET__", TARGET) + .replace("__COMMUNITY__", &community.to_string()) + .replace("__OTHER__", &other.to_string()); + sqlx::raw_sql(sqlx::AssertSqlSafe(seed)) + .execute(&pool) + .await + .unwrap(); + let before = tokens(&pool).await; + let npub = nostr::PublicKey::parse(TARGET) + .unwrap() + .to_bech32() + .unwrap(); + for (mode, key) in [ + (vec![], TARGET.to_uppercase()), + (vec!["--read-only"], npub), + (vec!["--print-only"], TARGET.to_owned()), + ] { + let rows = cli(&url, community, &key, &mode, 0).await; + assert_eq!(rows[0]["record"], "account_targets"); + assert_eq!(rows[0]["target"], TARGET); + let summary = rows.last().unwrap(); + assert_eq!(summary["record"], "account_handler_summary"); + assert_eq!(summary["items"], 35); + assert_eq!(summary["read_only"], true); + assert_eq!(summary["supported_scope_exhausted"], true); + assert_eq!(tokens(&pool).await, before); + } + assert!( + cli(&url, community, TARGET, &["--read-only", "--delete"], 2) + .await + .is_empty() + ); + let cap = cli(&url, community, TARGET, &["--max-items", "1"], 2).await; + assert_eq!(cap.last().unwrap()["supported_scope_exhausted"], false); + assert_eq!(tokens(&pool).await, before); + let cap = cli( + &url, + community, + TARGET, + &["--delete", "--max-items", "1"], + 2, + ) + .await; + assert_eq!(cap.last().unwrap()["items"], 1); + assert_eq!(cap.last().unwrap()["supported_scope_exhausted"], false); + assert_eq!( + tokens(&pool).await.as_array().unwrap().len(), + before.as_array().unwrap().len() - 1 + ); + let complete = cli(&url, community, TARGET, &["--delete"], 0).await; + assert_eq!(complete.last().unwrap()["items"], 34); + assert_eq!(complete.last().unwrap()["supported_scope_exhausted"], true); + assert_eq!(complete.last().unwrap()["account_erasure_complete"], false); + assert_eq!( + cli(&url, community, TARGET, &["--delete"], 0) + .await + .last() + .unwrap()["items"], + 0 + ); + let after = tokens(&pool).await; + let unrelated = |rows: &Value| { + rows.as_array() + .unwrap() + .iter() + .filter(|r| r["community_id"] == other.to_string()) + .cloned() + .collect::>() + }; + assert_eq!(unrelated(&after), unrelated(&before)); + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM entity_deletion_requests") + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(count, 0); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn global_and_frozen_scope_commands_use_explicit_saved_inputs() { + let url = std::env::var("BUZZ_TEST_DATABASE_URL") + .or_else(|_| std::env::var("DATABASE_URL")) + .unwrap(); + let pool = PgPool::connect(&url).await.unwrap(); + let binary = std::env::var_os("NEXTEST_BIN_EXE_buzz_admin") + .unwrap_or_else(|| env!("CARGO_BIN_EXE_buzz-admin").into()); + let community = Uuid::new_v4(); + sqlx::query("INSERT INTO communities(id,host) VALUES ($1,'scope-cli.example.org')") + .bind(community) + .execute(&pool) + .await + .unwrap(); + // No membership, profile or agent ownership: global records must still run. + sqlx::query("INSERT INTO product_feedback(event_id,submitter_pubkey,body,event_created_at) VALUES (decode($1,'hex'),decode($1,'hex'),'global private feedback',now())").bind(TARGET).execute(&pool).await.unwrap(); + let invoke = |args: Vec| { + let mut cmd = Command::new(&binary); + cmd.arg("user-deletions") + .args(args) + .env("DATABASE_URL", &url) + .env("BUZZ_AUTO_MIGRATE", "false") + .env("BUZZ_RELAY_PRIVATE_KEY", format!("{:064x}", 1)) + .env_remove("RELAY_OPERATOR_PUBKEYS") + .env_remove("RELAY_OWNER_PUBKEY") + .kill_on_drop(true); + cmd + }; + let scope = invoke(vec![ + "account-scope".into(), + "--pubkey".into(), + TARGET.into(), + ]) + .output() + .await + .unwrap(); + assert!( + scope.status.success(), + "{}", + String::from_utf8_lossy(&scope.stderr) + ); + let parsed: Value = serde_json::from_slice(&scope.stdout).unwrap(); + assert_eq!(parsed["communities"][0]["community"], community.to_string()); + let mut file = tempfile::NamedTempFile::new().unwrap(); + std::io::Write::write_all(&mut file, &scope.stdout).unwrap(); + let base = vec![ + "account-batches".into(), + "--scope-file".into(), + file.path().to_str().unwrap().into(), + "--actor".into(), + TARGET.into(), + ]; + let preview = invoke(base.clone()).output().await.unwrap(); + assert!( + preview.status.success(), + "{}", + String::from_utf8_lossy(&preview.stderr) + ); + assert_eq!( + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM product_feedback") + .fetch_one(&pool) + .await + .unwrap(), + 1 + ); + let mut delete = base; + delete.push("--delete".into()); + let blocked = invoke(delete.clone()) + .env("RELAY_OPERATOR_PUBKEYS", TARGET) + .output() + .await + .unwrap(); + assert!(!blocked.status.success()); + assert_eq!( + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM product_feedback") + .fetch_one(&pool) + .await + .unwrap(), + 1 + ); + let applied = invoke(delete.clone()).output().await.unwrap(); + assert!( + applied.status.success(), + "{}", + String::from_utf8_lossy(&applied.stderr) + ); + assert_eq!( + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM product_feedback") + .fetch_one(&pool) + .await + .unwrap(), + 0 + ); + let repeated = invoke(delete).output().await.unwrap(); + assert!(repeated.status.success()); + let last: Value = serde_json::from_str( + String::from_utf8_lossy(&repeated.stdout) + .lines() + .last() + .unwrap(), + ) + .unwrap(); + assert_eq!(last["record"], "account_scope_summary"); + assert_eq!(last["items"], 0); + assert_eq!(last["account_erasure_complete"], false); + let global = invoke(vec![ + "account-batches".into(), + "--pubkey".into(), + TARGET.into(), + "--global".into(), + "--actor".into(), + TARGET.into(), + ]) + .output() + .await + .unwrap(); + assert!(global.status.success()); + let first: Value = serde_json::from_str( + String::from_utf8_lossy(&global.stdout) + .lines() + .next() + .unwrap(), + ) + .unwrap(); + assert_eq!(first["scope"], "deployment_global"); +} diff --git a/crates/buzz-admin/tests/postgres_user_inventory.rs b/crates/buzz-admin/tests/postgres_user_inventory.rs index d0bca605b5..fc709413b4 100644 --- a/crates/buzz-admin/tests/postgres_user_inventory.rs +++ b/crates/buzz-admin/tests/postgres_user_inventory.rs @@ -1,4 +1,4 @@ -//! Exercise inventory access, demo completion, and unfinished real workflows. +//! Exercise the real CLI with SELECT-only access and no workflow tables. use nostr::ToBech32; use serde_json::Value; @@ -7,6 +7,9 @@ use tokio::process::Command; use url::Url; use uuid::Uuid; +mod user_inventory_support; +use user_inventory_support::{real_workflow_stops_at_gate, workflow_cli}; + fn admin_binary() -> std::ffi::OsString { // Nextest relocates binaries when extracting an archive. Cargo's build-time // path remains the fallback for local cargo test runs. @@ -193,84 +196,9 @@ fn invalid_inventory_key_fails_before_database_connection() { .contains("expected a 64-character hex public key or an npub")); } -async fn workflow_cli(url: &str, args: &[&str], success: bool) -> Value { - let output = tokio::time::timeout( - std::time::Duration::from_secs(20), - Command::new(admin_binary()) - .arg("user-deletions") - .args(args) - .env("DATABASE_URL", url) - .env("BUZZ_DB_POOL_SIZE", "1") - .kill_on_drop(true) - .output(), - ) - .await - .unwrap() - .unwrap(); - assert_eq!( - output.status.success(), - success, - "{args:?}: {}", - String::from_utf8_lossy(&output.stderr) - ); - if success { - serde_json::from_slice(&output.stdout).unwrap() - } else { - serde_json::json!({ - "exit_code": output.status.code(), - "stderr": String::from_utf8_lossy(&output.stderr), - }) - } -} - -async fn assert_real_workflow_stops_at_gate(url: &str, id: &str) -> Value { - let approved = workflow_cli(url, &["inspect", id], true).await; - let refused = workflow_cli(url, &["run", id, "--next-step"], false).await; - assert_eq!(refused["exit_code"], 5); - assert!(refused["stderr"] - .as_str() - .unwrap() - .contains("real workflow execution requires --delete")); - assert_eq!(workflow_cli(url, &["inspect", id], true).await, approved); - - let mut first_stage = None; - for _ in 0..2 { - let refused = workflow_cli(url, &["run", id, "--delete", "--next-step"], false).await; - assert_eq!(refused["exit_code"], 5); - assert!(refused["stderr"] - .as_str() - .unwrap() - .contains("real handler gate_user is not implemented")); - let inspected = workflow_cli(url, &["inspect", id], true).await; - assert_ne!(inspected["status"], "completed"); - assert!(inspected["completed_at"].is_null()); - assert!(inspected["lease_owner"].is_null()); - assert_eq!(inspected["target"], approved["target"]); - assert_eq!( - inspected["inventory_manifest"], - approved["inventory_manifest"] - ); - let stages = inspected["stage_history"].as_array().unwrap(); - assert_eq!(stages.len(), 1); - assert_eq!(stages[0]["stage"], "gate_user"); - assert_eq!(stages[0]["status"], "pending"); - assert_eq!(stages[0]["is_current"], true); - assert_eq!( - stages[0]["metadata_json"]["inputs"]["target"], - approved["target"] - ); - if let Some(first) = &first_stage { - assert_eq!(&stages[0]["id"], first); - } else { - first_stage = Some(stages[0]["id"].clone()); - } - } - workflow_cli(url, &["inspect", id], true).await -} - #[tokio::test] #[ignore = "requires Postgres"] -async fn inventory_submission_completes_demo_and_stops_unimplemented_real_workflow() { +async fn inventory_submission_completes_demo_but_refuses_unfinished_real_workflow() { let url = std::env::var("BUZZ_TEST_DATABASE_URL").unwrap(); let pool = PgPool::connect(&url).await.unwrap(); let key = "ab".repeat(32); @@ -340,7 +268,7 @@ async fn inventory_submission_completes_demo_and_stops_unimplemented_real_workfl ) .await; assert!(approved["stage_history"].as_array().unwrap().is_empty()); - let outcome = if subject == "demo" { + let done = if subject == "demo" { let stepped = workflow_cli(&url, &["run", id, "--next-step"], true).await; assert_eq!(stepped["stage_history"][0]["status"], "completed"); let first_id = stepped["stage_history"][0]["id"].clone(); @@ -354,10 +282,10 @@ async fn inventory_submission_completes_demo_and_stops_unimplemented_real_workfl .all(|s| s["status"] == "completed" && s["is_current"] == false)); done } else { - assert_real_workflow_stops_at_gate(&url, id).await + real_workflow_stops_at_gate(&url, id).await }; let inspected = workflow_cli(&url, &["inspect", id], true).await; - assert_eq!(inspected, outcome); + assert_eq!(inspected, done); // Hex and npub converge on the same saved request without rediscovery. let repeat = workflow_cli( &url, @@ -372,7 +300,7 @@ async fn inventory_submission_completes_demo_and_stops_unimplemented_real_workfl ) .await; for (field, value) in repeat.as_object().unwrap() { - assert_eq!(value, &outcome[field]); + assert_eq!(value, &done[field]); } workflow_cli( &url, @@ -387,7 +315,7 @@ async fn inventory_submission_completes_demo_and_stops_unimplemented_real_workfl ) .await; } - // Demo completion and real-handler refusal both preserve membership data. + // Demo completion and refusal of the real workflow both preserve membership. let count: i64 = sqlx::query_scalar("SELECT count(*) FROM channel_members WHERE community_id = $1 AND pubkey = decode($2, 'hex')") .bind(community).bind(&key).fetch_one(&pool).await.unwrap(); assert_eq!(count, 1); @@ -395,7 +323,7 @@ async fn inventory_submission_completes_demo_and_stops_unimplemented_real_workfl #[tokio::test] #[ignore = "requires Postgres"] -async fn inventory_approval_preserves_saved_account_identity_without_dummy_execution() { +async fn inventory_approval_and_resume_use_saved_account_identity_without_resolution() { let url = std::env::var("BUZZ_TEST_DATABASE_URL").unwrap(); let pool = PgPool::connect(&url).await.unwrap(); let saved = workflow_cli( @@ -433,7 +361,11 @@ async fn inventory_approval_preserves_saved_account_identity_without_dummy_execu true, ) .await; - let stopped = assert_real_workflow_stops_at_gate(&url, id).await; + let stopped = real_workflow_stops_at_gate(&url, id).await; assert_eq!(stopped["target"], account); assert_eq!(stopped["inventory_manifest"], saved["inventory_manifest"]); + for stage in stopped["stage_history"].as_array().unwrap() { + assert_eq!(stage["metadata_json"]["inputs"]["target"], account); + assert_eq!(stage["status"], "pending"); + } } diff --git a/crates/buzz-admin/tests/user_inventory_support/mod.rs b/crates/buzz-admin/tests/user_inventory_support/mod.rs new file mode 100644 index 0000000000..857fb43203 --- /dev/null +++ b/crates/buzz-admin/tests/user_inventory_support/mod.rs @@ -0,0 +1,94 @@ +//! Shared assertions for the inventory CLI's demo and real workflow journeys. + +use serde_json::Value; +use std::process::Output; +use tokio::process::Command; + +async fn workflow_output(url: &str, args: &[&str]) -> Output { + tokio::time::timeout( + std::time::Duration::from_secs(20), + Command::new(super::admin_binary()) + .arg("user-deletions") + .args(args) + .env("DATABASE_URL", url) + .env("BUZZ_DB_POOL_SIZE", "1") + .kill_on_drop(true) + .output(), + ) + .await + .unwrap() + .unwrap() +} + +pub async fn workflow_cli(url: &str, args: &[&str], success: bool) -> Value { + let output = workflow_output(url, args).await; + assert_eq!( + output.status.success(), + success, + "{args:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + if success { + serde_json::from_slice(&output.stdout).unwrap() + } else { + Value::Null + } +} + +async fn workflow_refuses(url: &str, args: &[&str], expected: &str) { + let output = workflow_output(url, args).await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(!output.status.success(), "{args:?} unexpectedly succeeded"); + assert!(stderr.contains(expected), "{args:?}: {stderr}"); +} + +pub async fn real_workflow_stops_at_gate(url: &str, id: &str) -> Value { + let approved = workflow_cli(url, &["inspect", id], true).await; + assert_eq!(approved["status"], "approved"); + assert!(approved["stage_history"].as_array().unwrap().is_empty()); + workflow_refuses( + url, + &["run", id, "--next-step"], + "real workflow execution requires --delete", + ) + .await; + // Refusing the missing flag must happen before claiming or initializing. + assert_eq!(workflow_cli(url, &["inspect", id], true).await, approved); + + let mut previous = approved; + for _ in 0..2 { + workflow_refuses( + url, + &["run", id, "--delete", "--next-step"], + "real handler gate_user is not implemented", + ) + .await; + let stopped = workflow_cli(url, &["inspect", id], true).await; + assert_eq!(stopped["status"], "running"); + let execution = &stopped["execution"]; + assert!(execution["lease_owner"].is_null()); + assert!(execution["lease_expires_at"].is_null()); + assert!(execution["completed_at"].is_null()); + // A new generation proves the retry reclaimed the released request. + assert_eq!( + execution["lease_generation"].as_i64().unwrap(), + previous["execution"]["lease_generation"].as_i64().unwrap() + 1 + ); + let stages = stopped["stage_history"].as_array().unwrap(); + assert_eq!(stages.len(), 1); + let stage = &stages[0]; + assert_eq!(stage["stage"], "gate_user"); + assert_eq!(stage["status"], "pending"); + assert_eq!(stage["is_current"], true); + assert!(stage["target_community_id"].is_null()); + assert!(stage["started_at"].is_null()); + assert!(stage["finished_at"].is_null()); + assert!(stage["metadata_json"].get("result").is_none()); + assert!(stage["metadata_json"].get("transition").is_none()); + if !previous["stage_history"].as_array().unwrap().is_empty() { + assert_eq!(stopped["stage_history"], previous["stage_history"]); + } + previous = stopped; + } + previous +} diff --git a/crates/buzz-db/src/store/channel.rs b/crates/buzz-db/src/store/channel.rs index 7473db74a3..e691bb0199 100644 --- a/crates/buzz-db/src/store/channel.rs +++ b/crates/buzz-db/src/store/channel.rs @@ -528,7 +528,7 @@ async fn get_channel_with_operation( } /// Read a live channel on `conn`. -async fn select_channel( +pub(crate) async fn select_channel( conn: &mut sqlx::PgConnection, community_id: CommunityId, channel_id: Uuid, @@ -812,6 +812,66 @@ pub fn group_metadata_uses_members(channel: &ChannelRecord) -> bool { /// The locked snapshot that feeds it reads only these members. pub const GROUP_ADMIN_ROLES: [MemberRole; 2] = [MemberRole::Owner, MemberRole::Admin]; +/// The tags of a channel's relay-signed NIP-29 kind:39001 admins event. +/// Shared by the relay, account cleanup and admin reconciliation. Only owners +/// and admins are listed, even when the supplied roster contains other roles. +pub fn group_admins_tags( + group_id: &str, + identity: &ChannelIdentity, + members: &[MemberRecord], +) -> std::result::Result, nostr::event::tag::Error> { + let mut tags = group_list_identity_tags(group_id, Some(identity))?; + for member in members.iter().filter(|member| { + GROUP_ADMIN_ROLES + .iter() + .any(|role| role.as_str() == member.role) + }) { + tags.push(nostr::Tag::parse([ + "p", + &hex::encode(&member.pubkey), + &member.role, + ])?); + } + Ok(tags) +} + +/// The tags of a channel's relay-signed NIP-29 kind:39002 members event. +/// Shared by the relay, account cleanup and admin reconciliation. A missing +/// channel identity still permits publishing the captured member roster. +pub fn group_members_tags( + group_id: &str, + identity: Option<&ChannelIdentity>, + members: &[MemberRecord], +) -> std::result::Result, nostr::event::tag::Error> { + let mut tags = group_list_identity_tags(group_id, identity)?; + for member in members { + // NIP-29: ["p", pubkey, relay_url, role]. The canonical relay is + // implicit because it signs the event, so relay_url stays empty. + tags.push(nostr::Tag::parse([ + "p", + &hex::encode(&member.pubkey), + "", + &member.role, + ])?); + } + Ok(tags) +} + +fn group_list_identity_tags( + group_id: &str, + identity: Option<&ChannelIdentity>, +) -> std::result::Result, nostr::event::tag::Error> { + let mut tags = vec![nostr::Tag::identifier(group_id)]; + if let Some(identity) = identity { + tags.extend(buzz_core::channel::group_state_identity_tags( + &identity.channel_type, + &identity.labels, + &identity.created_by, + )?); + } + Ok(tags) +} + /// The tags of a channel's relay-signed NIP-29 kind:39000 metadata event. /// /// This is the single builder for kind:39000: the relay's discovery emitter @@ -2340,6 +2400,92 @@ pub(crate) fn channel_ttl_lock_key(community: CommunityId, channel: Uuid) -> Str format!("buzz_channel_ttl:{}:{channel}", community.as_uuid()) } +#[cfg(test)] +mod group_list_tag_tests { + use super::*; + + #[test] + fn group_lists_preserve_identity_role_positions_and_roster_order() { + let identity = ChannelIdentity { + channel_type: "forum".into(), + labels: vec!["news".into(), "team".into()], + created_by: vec![0xab; 32], + }; + let roles = ["member", "owner", "guest", "admin", "bot", "unknown"]; + let members: Vec<_> = roles + .iter() + .enumerate() + .map(|(index, role)| MemberRecord { + channel_id: Uuid::nil(), + pubkey: vec![index as u8; 32], + role: (*role).into(), + joined_at: Utc::now(), + invited_by: None, + removed_at: None, + }) + .collect(); + let tag = |parts: &[&str]| { + parts + .iter() + .map(|part| (*part).to_string()) + .collect::>() + }; + let prefix = vec![ + tag(&["d", "group"]), + tag(&["t", "forum"]), + tag(&["t", "news"]), + tag(&["t", "team"]), + tag(&["P", &"ab".repeat(32)]), + ]; + let raw = |tags: Vec| { + tags.into_iter() + .map(|tag| tag.as_slice().to_vec()) + .collect::>() + }; + let mut admins = prefix.clone(); + admins.extend([ + tag(&["p", &"01".repeat(32), "owner"]), + tag(&["p", &"03".repeat(32), "admin"]), + ]); + assert_eq!( + raw(group_admins_tags("group", &identity, &members).unwrap()), + admins + ); + let mut roster = prefix.clone(); + roster.extend([ + tag(&["p", &"00".repeat(32), "", "member"]), + tag(&["p", &"01".repeat(32), "", "owner"]), + tag(&["p", &"02".repeat(32), "", "guest"]), + tag(&["p", &"03".repeat(32), "", "admin"]), + tag(&["p", &"04".repeat(32), "", "bot"]), + tag(&["p", &"05".repeat(32), "", "unknown"]), + ]); + assert_eq!( + raw(group_members_tags("group", Some(&identity), &members).unwrap()), + roster + ); + assert_eq!( + raw(group_admins_tags("group", &identity, &[]).unwrap()), + prefix + ); + assert_eq!( + raw(group_members_tags("group", Some(&identity), &[]).unwrap()), + prefix + ); + let without_identity = std::iter::once(tag(&["d", "group"])) + .chain(roster.into_iter().skip(prefix.len())) + .collect::>(); + assert_eq!( + raw(group_members_tags("group", None, &members).unwrap()), + without_identity + ); + assert_eq!( + raw(group_members_tags("group", None, &[]).unwrap()), + vec![tag(&["d", "group"])] + ); + } +} + #[cfg(test)] mod group_metadata_tag_tests { use super::*; diff --git a/crates/buzz-db/src/store/entity_deletion/leases.rs b/crates/buzz-db/src/store/entity_deletion/leases.rs index f46f03ea03..47aca701fc 100644 --- a/crates/buzz-db/src/store/entity_deletion/leases.rs +++ b/crates/buzz-db/src/store/entity_deletion/leases.rs @@ -188,7 +188,7 @@ pub(in crate::store) async fn lock_owned( } pub(in crate::store) async fn validate_approved_inventory( - tx: &mut Tx<'_>, + tx: &mut sqlx::PgConnection, request: &EntityRequest, ) -> Result<()> { let digest = validated_inventory_digest(request)?; @@ -198,7 +198,7 @@ pub(in crate::store) async fn validate_approved_inventory( ) .bind(request.id) .bind(digest) - .fetch_one(&mut **tx) + .fetch_one(&mut *tx) .await?; if !approved { return Err(DbError::DeletionSafety( diff --git a/crates/buzz-db/src/store/relay_operators.rs b/crates/buzz-db/src/store/relay_operators.rs index 41b45a9ac6..fe59ca0d6f 100644 --- a/crates/buzz-db/src/store/relay_operators.rs +++ b/crates/buzz-db/src/store/relay_operators.rs @@ -43,7 +43,7 @@ async fn acquire_operator_lock(tx: &mut Transaction<'_, Postgres>, pubkey: &[u8] /// Take the transaction-scoped roster-wide advisory lock. Serializes all /// operator-removing mutations against each other so the last-operator check /// sees a stable count. -async fn acquire_roster_lock(tx: &mut Transaction<'_, Postgres>) -> Result<()> { +pub(crate) async fn acquire_roster_lock(tx: &mut Transaction<'_, Postgres>) -> Result<()> { sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))") .bind(OPERATOR_ROSTER_LOCK) .execute(&mut **tx) @@ -205,16 +205,28 @@ pub async fn remove( .await?; let mut tx = sqlx::Transaction::begin(connection, None).await?; + let removed = remove_in_transaction(&mut tx, pubkey, actor, config_operator_exists).await?; + tx.commit().await?; + Ok(removed) +} + +/// Reuse the roster invariant and audit write inside offline cleanup's batch. +pub(crate) async fn remove_in_transaction( + tx: &mut Transaction<'_, Postgres>, + pubkey: &[u8], + actor: &[u8], + config_operator_exists: bool, +) -> Result { // Serialize against every other operator-removing mutation before the // delete so the post-delete count reflects a stable roster. - acquire_roster_lock(&mut tx).await?; + acquire_roster_lock(tx).await?; // Capture the pre-image role the delete removes; also gates the audit row // so a no-op delete of an absent pubkey writes nothing. let prev_role: Option = sqlx::query_scalar("DELETE FROM relay_operators WHERE pubkey = $1 RETURNING role") .bind(pubkey) - .fetch_optional(&mut *tx) + .fetch_optional(&mut **tx) .await?; let removed = prev_role.is_some(); @@ -229,17 +241,16 @@ pub async fn remove( .bind(actor) .bind(pubkey) .bind(prev_role.as_deref()) - .execute(&mut *tx) + .execute(&mut **tx) .await?; // Deleting an operator can empty the roster. Dropping the tx here rolls // the delete and its audit row back. - if !config_operator_exists && db_operator_count(&mut tx).await? == 0 { + if !config_operator_exists && db_operator_count(tx).await? == 0 { return Err(DbError::LastOperator); } } - tx.commit().await?; Ok(removed) } diff --git a/crates/buzz-db/src/store/user_deletion/account_batches/community_memberships.rs b/crates/buzz-db/src/store/user_deletion/account_batches/community_memberships.rs new file mode 100644 index 0000000000..5f9fdf28e2 --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/account_batches/community_memberships.rs @@ -0,0 +1,115 @@ +//! Community membership and its signed NIP-43 roster commit together. +use super::*; +use buzz_core::CommunityId; + +impl UserDeletionStore { + pub(super) async fn preflight_community_membership( + &self, + conn: &mut PgConnection, + community: Uuid, + targets: &[String], + ) -> Result<()> { + let exists: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM relay_members WHERE community_id=$1 AND pubkey=ANY($2))", + ) + .bind(community) + .bind(targets) + .fetch_one(&mut *conn) + .await?; + if exists { + let signer = self.account_snapshot_signer.as_ref().ok_or_else(|| { + invalid("membership cleanup requires the existing relay signing key (BUZZ_RELAY_PRIVATE_KEY)") + })?; + check_signer(conn, community, signer).await?; + } + Ok(()) + } + + pub(super) async fn delete_community_membership( + &self, + options: &Options, + op: &Operation, + writer: &mut impl Write, + stage: Option<(&crate::entity_deletion::EntityLease, Uuid)>, + summary: &mut AccountBatchSummary, + ) -> Result<()> { + let community = options + .community + .ok_or_else(|| invalid("membership cleanup requires a community"))?; + let mut raw = self.pool.begin().await?; + timeouts(&mut raw).await?; + if let Some((lease, id)) = stage { + validate_stage(&mut raw, lease, id, options).await?; + } + ownership::recheck(&mut raw, options, true).await?; + // Admission precedes the member row lock, matching membership writers. + let mut tx = crate::AdmittedTx::admit( + raw, + &crate::deletion::DeletionStore::new(self.pool.clone()), + CommunityId::from_uuid(community), + ) + .await?; + let keys = select(tx.conn(), options, op, None, true, summary).await?; + if keys.is_empty() { + tx.commit().await?; + return Ok(()); + } + if summary.items == options.max_items { + summary.supported_scope_exhausted = false; + return Ok(()); + } + let signer = self + .account_snapshot_signer + .as_ref() + .ok_or_else(|| invalid("missing relay signing key"))?; + check_signer(tx.conn(), community, signer).await?; + batch(writer, options, op, &keys, summary)?; + // The selected row is locked: a concurrent ownership grant cannot turn + // this target into an owner between this predicate and the delete. + let removed = sqlx::query( + "DELETE FROM relay_members WHERE community_id=$1 AND pubkey=$2 AND role<>'owner'", + ) + .bind(community) + .bind(&options.pubkey) + .execute(tx.conn()) + .await? + .rows_affected(); + if removed != 1 { + return Err(invalid( + "community owner handoff required; membership removal rolled back", + )); + } + if let Some((lease, id)) = stage { + validate_stage(tx.conn(), lease, id, options).await?; + } + // Roster lock is last, as in the normal membership write protocol. + crate::relay_members::write_nip43_membership_snapshot(&mut tx, signer).await?; + tx.commit().await?; + summary.items += 1; + summary.batches += 1; + line( + writer, + &json!({"record":"batch_committed", "number":summary.batches, + "table":op.table,"action":op.action,"items":1,"saved_community_roster":true}), + ) + } +} + +async fn check_signer( + conn: &mut PgConnection, + community: Uuid, + signer: &nostr::Keys, +) -> Result<()> { + let mismatch: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM events WHERE community_id=$1 AND kind=13534 + AND channel_id IS NULL AND deleted_at IS NULL AND pubkey<>$2)", + ) + .bind(community) + .bind(signer.public_key().to_bytes().as_slice()) + .fetch_one(conn) + .await?; + if mismatch { + return Err(invalid("relay signing key differs from existing community roster; membership removal rolled back")); + } + Ok(()) +} diff --git a/crates/buzz-db/src/store/user_deletion/account_batches/community_memberships_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/account_batches/community_memberships_postgres_tests.rs new file mode 100644 index 0000000000..29f4d6e200 --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/account_batches/community_memberships_postgres_tests.rs @@ -0,0 +1,127 @@ +use super::*; +use buzz_core::CommunityId; +use nostr::JsonUtil; + +async fn rosters(pool: &PgPool) -> Value { + sqlx::query_scalar("SELECT COALESCE(jsonb_agg(to_jsonb(e) ORDER BY community_id,created_at,id),'[]') FROM events e WHERE kind=13534") + .fetch_one(pool).await.unwrap() +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn community_only_membership_refresh_is_atomic_and_preserves_other_community() { + let f = Fixture::new().await; + // Community membership alone must require the signing key. + sqlx::query("DELETE FROM channel_members WHERE community_id=$1 AND pubkey=decode($2,'hex')") + .bind(f.options.community) + .bind(TARGET) + .execute(&f.pool) + .await + .unwrap(); + let signer = nostr::Keys::parse(&format!("{:064x}", 1)).unwrap(); + for community in [f.options.community, f.other] { + let mut tx = crate::begin_community_event_write_transaction( + &f.pool, + CommunityId::from_uuid(community), + crate::observability::WriterOperation::EventWrite, + ) + .await + .unwrap(); + crate::relay_members::write_nip43_membership_snapshot(&mut tx, &signer) + .await + .unwrap(); + tx.commit().await.unwrap(); + } + let before = f.snapshot().await; + let old_rosters = rosters(&f.pool).await; + let unsigned = Db::from_pool(f.pool.clone()).user_deletion_store(); + unsigned + .run_account_batches(&f.options, ExecutionMode::ReadOnly, &mut Vec::new(), None) + .await + .unwrap(); + for store in [ + unsigned, + Db::from_pool(f.pool.clone()) + .user_deletion_store() + .with_account_snapshot_signer(nostr::Keys::parse(&format!("{:064x}", 2)).unwrap()), + ] { + assert!(store + .run_account_batches(&f.options, ExecutionMode::Delete, &mut Vec::new(), None) + .await + .is_err()); + assert_eq!(f.snapshot().await, before); + assert_eq!(rosters(&f.pool).await, old_rosters); + } + // Fail the replacement insert after the member DELETE and old-head retirement. + sqlx::query("ALTER TABLE events ADD CONSTRAINT account_test_reject_community_roster CHECK (kind<>13534) NOT VALID") + .execute(&f.pool).await.unwrap(); + let error = f + .run(ExecutionMode::Delete, &mut Vec::new()) + .await + .unwrap_err(); + assert!(error + .to_string() + .contains("account_test_reject_community_roster")); + assert_eq!(f.snapshot().await["relay_members"], before["relay_members"]); + assert_eq!(rosters(&f.pool).await, old_rosters); + sqlx::query("ALTER TABLE events DROP CONSTRAINT account_test_reject_community_roster") + .execute(&f.pool) + .await + .unwrap(); + let mut output = Vec::new(); + f.run(ExecutionMode::Delete, &mut output).await.unwrap(); + assert!(records(&output) + .iter() + .any(|r| r["saved_community_roster"] == true)); + let current: Vec = sqlx::query_scalar("SELECT jsonb_build_object('id',encode(id,'hex'),'pubkey',encode(pubkey,'hex'),'created_at',extract(epoch FROM created_at)::bigint,'kind',kind,'tags',tags,'content',content,'sig',encode(sig,'hex')) FROM events WHERE community_id=$1 AND kind=13534 AND deleted_at IS NULL") + .bind(f.options.community).fetch_all(&f.pool).await.unwrap(); + assert_eq!(current.len(), 1); + nostr::Event::from_json(current[0].to_string()) + .unwrap() + .verify() + .unwrap(); + let expected: Vec<(String, String)> = sqlx::query_as( + "SELECT pubkey,role::text FROM relay_members WHERE community_id=$1 ORDER BY pubkey", + ) + .bind(f.options.community) + .fetch_all(&f.pool) + .await + .unwrap(); + let actual: BTreeSet<_> = current[0]["tags"] + .as_array() + .unwrap() + .iter() + .filter(|tag| tag[0] == "member") + .map(Value::to_string) + .collect(); + assert_eq!( + actual, + expected + .into_iter() + .map(|(key, role)| json!(["member", key, role]).to_string()) + .collect() + ); + assert!(!current[0]["tags"] + .as_array() + .unwrap() + .iter() + .any(|tag| tag[1] == TARGET)); + let after = rosters(&f.pool).await; + let other = |rows: &Value| { + rows.as_array() + .unwrap() + .iter() + .filter(|r| r["community_id"] == f.other.to_string()) + .cloned() + .collect::>() + }; + assert_eq!(other(&after), other(&old_rosters)); + assert_eq!( + f.run(ExecutionMode::Delete, &mut Vec::new()) + .await + .unwrap() + .items, + 0 + ); + assert_eq!(rosters(&f.pool).await, after); +} diff --git a/crates/buzz-db/src/store/user_deletion/account_batches/fixture.sql b/crates/buzz-db/src/store/user_deletion/account_batches/fixture.sql new file mode 100644 index 0000000000..4a88bdce39 --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/account_batches/fixture.sql @@ -0,0 +1,50 @@ +-- Test-only data: identical row identifiers in two communities, three users, +-- and enough UUID/composite keys to cross every multirow pagination boundary. +BEGIN; +CREATE TEMP TABLE account_fixture_keys AS +SELECT community, pubkey, + CASE WHEN pubkey = repeat('33',32) THEN pubkey ELSE '__TARGET__' END AS actor +FROM (VALUES ('__COMMUNITY__'::uuid), ('__OTHER__'::uuid)) c(community) +CROSS JOIN (VALUES ('__TARGET__'), (repeat('22',32)), (repeat('33',32))) p(pubkey); +INSERT INTO communities(id,host) +SELECT DISTINCT community, community::text || '.example.org' FROM account_fixture_keys; +INSERT INTO users(community_id,pubkey) +SELECT community,decode(pubkey,'hex') FROM account_fixture_keys; +INSERT INTO relay_members(community_id,pubkey,role,added_by) +SELECT community,pubkey,'member',actor FROM account_fixture_keys; +INSERT INTO pubkey_allowlist(community_id,pubkey,added_by) +SELECT community,decode(pubkey,'hex'),decode(actor,'hex') FROM account_fixture_keys; +INSERT INTO channels(community_id,id,name,created_by) +SELECT DISTINCT community,md5(n::text)::uuid,'fixture-'||n,decode(repeat('22',32),'hex') +FROM account_fixture_keys CROSS JOIN generate_series(1,3) n; +INSERT INTO channel_members(community_id,channel_id,pubkey,invited_by,removed_by,removed_at) +SELECT community,md5(n::text)::uuid,decode(pubkey,'hex'),decode(actor,'hex'), + CASE WHEN n > 1 THEN decode(actor,'hex') END, + CASE WHEN n > 1 THEN now() END +FROM account_fixture_keys CROSS JOIN generate_series(1,3) n; +INSERT INTO api_tokens(community_id,id,owner_pubkey,token_hash,name,scopes,revoked_by,revoked_at,expires_at) +SELECT community,md5(pubkey||n)::uuid,decode(pubkey,'hex'), + decode(md5(pubkey||n)||md5(pubkey||n),'hex'),'fixture','[]', + CASE WHEN n > 1 THEN decode(actor,'hex') END, + CASE WHEN n > 1 THEN now() END, CASE WHEN n = 3 THEN now() - interval '1 day' END +FROM account_fixture_keys CROSS JOIN generate_series(1,3) n; +INSERT INTO relay_invites(community_id,id,created_by,token_hash,expires_at) +SELECT community,md5(pubkey||n)::uuid,pubkey,decode(md5(pubkey||n)||md5(pubkey||n),'hex'),now() +FROM account_fixture_keys CROSS JOIN generate_series(1,3) n; +INSERT INTO join_policy_acceptances(community_id,pubkey,policy_version) +SELECT community,pubkey,lpad(n::text,64,'0') FROM account_fixture_keys CROSS JOIN generate_series(1,3) n; +INSERT INTO personal_read_accounts(community_id,actor) +SELECT community,decode(pubkey,'hex') FROM account_fixture_keys; +INSERT INTO personal_read_frontiers(community_id,actor,channel_id,root_id,through_timestamp) +SELECT community,decode(pubkey,'hex'),md5(n::text)::uuid,decode(lpad(r::text,64,'0'),'hex'),now() +FROM account_fixture_keys CROSS JOIN generate_series(1,3) n CROSS JOIN generate_series(1,3) r; +INSERT INTO archived_identities(community_id,pubkey,actor,consent_path,replaced_by,request_event_id) +SELECT community,pubkey,pubkey,'self',actor,'fixture' FROM account_fixture_keys; +INSERT INTO parameterized_event_watermarks(community_id,pubkey,kind,d_tag,created_at,event_id) +SELECT community,decode(pubkey,'hex'),30078,'fixture',now(),decode(pubkey,'hex') FROM account_fixture_keys; +UPDATE relay_members SET updated_at='2000-01-01T00:00:00Z' +WHERE community_id IN ('__COMMUNITY__','__OTHER__'); +UPDATE channel_members SET sync_modified_at='2000-01-01T00:00:00Z' +WHERE community_id IN ('__COMMUNITY__','__OTHER__'); +DROP TABLE account_fixture_keys; +COMMIT; diff --git a/crates/buzz-db/src/store/user_deletion/account_batches/memberships.rs b/crates/buzz-db/src/store/user_deletion/account_batches/memberships.rs new file mode 100644 index 0000000000..0b620d6a31 --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/account_batches/memberships.rs @@ -0,0 +1,197 @@ +//! Membership removal and the three signed discovery lists share one commit. +use super::*; +use buzz_core::CommunityId; +use nostr::{EventBuilder, Kind, Tag, Timestamp}; + +impl UserDeletionStore { + pub(super) async fn preflight_memberships( + &self, + community: Uuid, + targets: &[String], + ) -> Result<()> { + let mut tx = self.pool.begin().await?; + timeouts(&mut tx).await?; + self.preflight_community_membership(&mut tx, community, targets) + .await?; + let targets: Vec> = targets + .iter() + .map(|key| hex::decode(key).map_err(|_| invalid("invalid target"))) + .collect::>()?; + let has_members: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM channel_members WHERE community_id=$1 AND pubkey=ANY($2))", + ) + .bind(community) + .bind(&targets) + .fetch_one(&mut *tx) + .await?; + if !has_members { + tx.rollback().await?; + return Ok(()); + } + let signer = self.account_snapshot_signer.as_ref().ok_or_else(|| { + invalid( + "membership cleanup requires the existing relay signing key (BUZZ_RELAY_PRIVATE_KEY)", + ) + })?; + let mismatch: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM events e WHERE e.community_id=$1 AND e.kind IN (39000,39001,39002) AND e.deleted_at IS NULL AND e.pubkey<>$3 AND EXISTS(SELECT 1 FROM channel_members m WHERE m.community_id=e.community_id AND m.channel_id=e.channel_id AND m.pubkey=ANY($2)))", + ).bind(community).bind(&targets).bind(signer.public_key().to_bytes().as_slice()).fetch_one(&mut *tx).await?; + if mismatch { + return Err(invalid( + "relay signing key differs from existing channel lists; no cleanup performed", + )); + } + tx.rollback().await?; + Ok(()) + } + + pub(super) async fn delete_memberships( + &self, + options: &Options, + op: &Operation, + writer: &mut impl Write, + stage: Option<(&crate::entity_deletion::EntityLease, Uuid)>, + summary: &mut AccountBatchSummary, + ) -> Result<()> { + let community = CommunityId::from_uuid( + options + .community + .ok_or_else(|| invalid("membership cleanup requires a community"))?, + ); + loop { + let mut raw = self.pool.begin().await?; + timeouts(&mut raw).await?; + if let Some((lease, id)) = stage { + validate_stage(&mut raw, lease, id, options).await?; + } + ownership::recheck(&mut raw, options, true).await?; + // Discover without row locks: replacement locks must precede the + // membership lock, which must precede membership row locks. + let keys = select(&mut raw, options, op, None, false, summary).await?; + if keys.is_empty() { + raw.rollback().await?; + break; + } + if summary.items == options.max_items { + summary.supported_scope_exhausted = false; + raw.rollback().await?; + break; + } + let channel: Uuid = keys[0]["channel_id"] + .as_str() + .ok_or_else(|| invalid("missing channel key"))? + .parse() + .map_err(|_| invalid("invalid channel key"))?; + let signer = self + .account_snapshot_signer + .as_ref() + .ok_or_else(|| invalid("missing relay signing key"))?; + let relay = signer.public_key().to_bytes(); + let mut tx = crate::AdmittedTx::admit( + raw, + &crate::deletion::DeletionStore::new(self.pool.clone()), + community, + ) + .await?; + for kind in [39000, 39001, 39002] { + crate::replaceable::take_replacement_lock(&mut tx, kind, &relay, Some(channel)) + .await?; + } + crate::channel_members::acquire_channel_membership_lock(tx.conn(), community, channel) + .await?; + let mismatch: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM events WHERE community_id=$1 AND channel_id=$2 AND kind IN (39000,39001,39002) AND deleted_at IS NULL AND pubkey<>$3)") + .bind(community.as_uuid()).bind(channel).bind(relay.as_slice()).fetch_one(tx.conn()).await?; + if mismatch { + return Err(invalid( + "relay signing key changed; channel removal rolled back", + )); + } + batch(writer, options, op, &keys, summary)?; + let removed = sqlx::query("DELETE FROM channel_members WHERE community_id=$1 AND channel_id=$2 AND pubkey=decode($3,'hex')") + .bind(community.as_uuid()).bind(channel).bind(&options.pubkey).execute(tx.conn()).await?.rows_affected(); + if removed != 1 { + return Err(invalid("membership changed; rerun cleanup")); + } + let saved_lists = rebuild(&mut tx, channel, signer).await?; + if let Some((lease, id)) = stage { + validate_stage(tx.conn(), lease, id, options).await?; + } + tx.commit().await?; + summary.items += 1; + summary.batches += 1; + line( + writer, + &json!({"record":"batch_committed", "number":summary.batches, + "table":op.table,"action":op.action,"items":1,"channel":channel,"saved_channel_lists":saved_lists}), + )?; + } + Ok(()) + } +} + +pub(super) async fn rebuild( + tx: &mut crate::AdmittedTx, + channel_id: Uuid, + signer: &nostr::Keys, +) -> Result { + let community = tx.community(); + let channel = match crate::channel::select_channel(tx.conn(), community, channel_id).await { + Ok(channel) => channel, + Err(DbError::ChannelNotFound(_)) => { + // Deleted channels can retain membership rows. Never resurrect their + // discovery heads; retire any remaining heads with the removal. + sqlx::query(superseded_with_mentions_sql!( + "UPDATE events SET deleted_at=NOW() WHERE community_id=$1 AND channel_id=$2 AND kind IN (39000,39001,39002) AND deleted_at IS NULL" + )).bind(community.as_uuid()).bind(channel_id).execute(tx.conn()).await?; + return Ok(0); + } + Err(error) => return Err(error), + }; + let members = + crate::channel_members::select_active_members(tx.conn(), community, channel_id).await?; + for kind in [39000, 39001, 39002] { + let tags = if kind == 39000 { + crate::channel::group_metadata_tags(&channel, &members) + .into_iter() + .map(Tag::parse) + .collect::, _>>() + .map_err(|e| invalid(e.to_string()))? + } else if kind == 39001 { + crate::channel::group_admins_tags( + &channel_id.to_string(), + &channel.identity(), + &members, + ) + .map_err(|e| invalid(e.to_string()))? + } else { + crate::channel::group_members_tags( + &channel_id.to_string(), + Some(&channel.identity()), + &members, + ) + .map_err(|e| invalid(e.to_string()))? + }; + let latest: Option> = sqlx::query_scalar("SELECT max(created_at) FROM events WHERE community_id=$1 AND channel_id=$2 AND kind=$3 AND pubkey=$4 AND deleted_at IS NULL") + .bind(community.as_uuid()).bind(channel_id).bind(kind).bind(signer.public_key().to_bytes().as_slice()).fetch_one(tx.conn()).await?; + let now = Timestamp::now().as_secs(); + let timestamp = latest + .map(|t| (t.timestamp() as u64).saturating_add(1)) + .unwrap_or(now) + .max(now); + let event = EventBuilder::new(Kind::Custom(kind as u16), "") + .tags(tags) + .allow_self_tagging() + .custom_created_at(Timestamp::from(timestamp)) + .sign_with_keys(signer) + .map_err(|e| invalid(e.to_string()))?; + let (_, inserted) = + crate::replaceable::replace_addressable_event_under_lock(tx, &event, Some(channel_id)) + .await?; + if !inserted { + return Err(invalid( + "channel list replacement failed; membership removal rolled back", + )); + } + } + Ok(3) +} diff --git a/crates/buzz-db/src/store/user_deletion/account_batches/memberships_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/account_batches/memberships_postgres_tests.rs new file mode 100644 index 0000000000..b3c0e6038a --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/account_batches/memberships_postgres_tests.rs @@ -0,0 +1,253 @@ +use super::*; +use buzz_core::CommunityId; +use nostr::JsonUtil; + +async fn saved_lists(pool: &PgPool) -> Value { + sqlx::query_scalar("SELECT COALESCE(jsonb_agg(to_jsonb(e) ORDER BY community_id,kind,channel_id,created_at,id),'[]') FROM events e WHERE kind IN (39000,39001,39002)") + .fetch_one(pool).await.unwrap() +} + +async fn seed_lists(f: &Fixture) { + // Include a DM (its metadata contains members), an admin removal, an empty + // active roster, and the relay itself in a roster (self-tagging). + sqlx::query("UPDATE channels SET channel_type='dm' WHERE name='fixture-1'") + .execute(&f.pool) + .await + .unwrap(); + sqlx::query("UPDATE channel_members SET role='owner' WHERE pubkey=decode($1,'hex')") + .bind(TARGET) + .execute(&f.pool) + .await + .unwrap(); + let signer = nostr::Keys::parse(&format!("{:064x}", 1)).unwrap(); + let channels: Vec<(Uuid, Uuid)> = + sqlx::query_as("SELECT community_id,id FROM channels ORDER BY community_id,id") + .fetch_all(&f.pool) + .await + .unwrap(); + for (community, channel) in channels { + let mut tx = crate::begin_community_event_write_transaction( + &f.pool, + CommunityId::from_uuid(community), + crate::observability::WriterOperation::EventWrite, + ) + .await + .unwrap(); + for kind in [39000, 39001, 39002] { + crate::replaceable::take_replacement_lock( + &mut tx, + kind, + &signer.public_key().to_bytes(), + Some(channel), + ) + .await + .unwrap(); + } + crate::channel_members::acquire_channel_membership_lock( + tx.conn(), + CommunityId::from_uuid(community), + channel, + ) + .await + .unwrap(); + memberships::rebuild(&mut tx, channel, &signer) + .await + .unwrap(); + tx.commit().await.unwrap(); + } +} + +async fn assert_current_lists(f: &Fixture) { + let rows: Vec = sqlx::query_scalar("SELECT jsonb_build_object('id',encode(id,'hex'),'pubkey',encode(pubkey,'hex'),'created_at',extract(epoch FROM created_at)::bigint,'kind',kind,'tags',tags,'content',content,'sig',encode(sig,'hex')) FROM events WHERE community_id=$1 AND kind IN (39000,39001,39002) AND deleted_at IS NULL ORDER BY channel_id,kind") + .bind(f.options.community).fetch_all(&f.pool).await.unwrap(); + assert_eq!(rows.len(), 9); + for row in rows { + let event = nostr::Event::from_json(row.to_string()).unwrap(); + event.verify().unwrap(); + let channel = Uuid::parse_str(event.tags.identifier().unwrap()).unwrap(); + let roster: Vec<(String,String)> = sqlx::query_as("SELECT encode(pubkey,'hex'),role::text FROM channel_members WHERE community_id=$1 AND channel_id=$2 AND removed_at IS NULL ORDER BY pubkey") + .bind(f.options.community).bind(channel).fetch_all(&f.pool).await.unwrap(); + let kind = row["kind"].as_i64().unwrap(); + let expected: BTreeSet<_> = roster + .into_iter() + .filter(|(_, role)| kind != 39001 || matches!(role.as_str(), "owner" | "admin")) + .map(|(key, role)| { + if kind == 39002 { + json!(["p", key, "", role]).to_string() + } else if kind == 39001 { + json!(["p", key, role]).to_string() + } else { + json!(["p", key]).to_string() + } + }) + .collect(); + let actual: BTreeSet<_> = row["tags"] + .as_array() + .unwrap() + .iter() + .filter(|t| t[0] == "p") + .map(Value::to_string) + .collect(); + if kind != 39000 + || row["tags"] + .as_array() + .unwrap() + .contains(&json!(["t", "dm"])) + { + assert_eq!(actual, expected); + } else { + assert!(actual.is_empty()); + } + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn signed_lists_rollback_on_write_failure_then_resume_without_changing_other_community() { + journey().await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn migration_schema_signed_lists_rollback_and_resume() { + let pool = PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + Db::from_pool(pool.clone()).migrate().await.unwrap(); + pool.close().await; + journey().await; +} + +async fn journey() { + let mut f = Fixture::new().await; + seed_lists(&f).await; + let before = f.snapshot().await; + let lists = saved_lists(&f.pool).await; + f.run(ExecutionMode::ReadOnly, &mut Vec::new()) + .await + .unwrap(); + assert_eq!(f.snapshot().await, before); + assert_eq!(saved_lists(&f.pool).await, lists); + // Neither missing nor wrong key may delete even an earlier token batch. + for signer in [ + None, + Some(nostr::Keys::parse(&format!("{:064x}", 2)).unwrap()), + ] { + let mut store = Db::from_pool(f.pool.clone()).user_deletion_store(); + if let Some(signer) = signer { + store = store.with_account_snapshot_signer(signer); + } + assert!(store + .run_account_batches(&f.options, ExecutionMode::Delete, &mut Vec::new(), None) + .await + .is_err()); + assert_eq!(f.snapshot().await, before); + } + // Fail the LAST list insert after membership removal and two successful + // list writes on that transaction. No test-only branch in production. + sqlx::query("ALTER TABLE events ADD CONSTRAINT account_test_reject_members CHECK (kind<>39002) NOT VALID") + .execute(&f.pool).await.unwrap(); + assert!(f + .run(ExecutionMode::Delete, &mut Vec::new()) + .await + .unwrap_err() + .to_string() + .contains("account_test_reject_members")); + assert_eq!( + f.snapshot().await["channel_members"], + before["channel_members"] + ); + assert_eq!(saved_lists(&f.pool).await, lists); + sqlx::query("ALTER TABLE events DROP CONSTRAINT account_test_reject_members") + .execute(&f.pool) + .await + .unwrap(); + // Interrupt the process while its last list is blocked, after the other + // list replacements and membership DELETE ran but before COMMIT. + let mut blocker = f.pool.begin().await.unwrap(); + let pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&mut *blocker) + .await + .unwrap(); + sqlx::query("SELECT id FROM events WHERE community_id=$1 AND kind=39002 AND deleted_at IS NULL FOR UPDATE") + .bind(f.options.community).fetch_all(&mut *blocker).await.unwrap(); + let store = f.store(); + let options = AccountBatchOptions { + community: f.options.community, + pubkey: TARGET.into(), + batch_size: 2, + max_items: 1000, + }; + let task = tokio::spawn(async move { + store + .run_account_batches(&options, ExecutionMode::Delete, &mut Vec::new(), None) + .await + }); + let reached = tokio::time::timeout(std::time::Duration::from_secs(2), async { + loop { + let blocked: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE datname=current_database() AND $1=ANY(pg_blocking_pids(pid)))") + .bind(pid).fetch_one(&f.pool).await.unwrap(); + if blocked { break; } + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + }).await; + task.abort(); + let stopped = task.await; + blocker.rollback().await.unwrap(); + reached.unwrap(); + assert!(stopped.unwrap_err().is_cancelled()); + assert_eq!( + f.snapshot().await["channel_members"], + before["channel_members"] + ); + assert_eq!(saved_lists(&f.pool).await, lists); + // One channel commits, then the command stops. Its lists must already agree + // with its table; channels not yet processed still agree with theirs. + f.options.max_items = 1; + let partial = f.run(ExecutionMode::Delete, &mut Vec::new()).await.unwrap(); + assert_eq!(partial.items, 1); + assert!(!partial.supported_scope_exhausted); + assert_current_lists(&f).await; + f.options.max_items = 1000; + f.run(ExecutionMode::Delete, &mut Vec::new()).await.unwrap(); + assert_current_lists(&f).await; + let after = saved_lists(&f.pool).await; + let other = |v: &Value| { + v.as_array() + .unwrap() + .iter() + .filter(|r| r["community_id"] == f.other.to_string()) + .cloned() + .collect::>() + }; + assert_eq!(other(&after), other(&lists)); + assert!(after + .as_array() + .unwrap() + .iter() + .filter( + |r| r["community_id"] == f.options.community.to_string() && r["deleted_at"].is_null() + ) + .all(|r| !r["tags"] + .as_array() + .unwrap() + .iter() + .any(|t| t[0] == "p" && t[1] == TARGET))); + assert_eq!( + f.run(ExecutionMode::Delete, &mut Vec::new()) + .await + .unwrap() + .items, + 0 + ); + assert_eq!(saved_lists(&f.pool).await, after); + // Old channel deletion leaves member rows. Account cleanup must finish + // without bringing that channel's discovery lists back to life. + let deleted: Uuid=sqlx::query_scalar("UPDATE channels SET deleted_at=now() WHERE community_id=$1 AND name='fixture-3' RETURNING id") + .bind(f.other).fetch_one(&f.pool).await.unwrap(); + f.options.community = f.other; + f.run(ExecutionMode::Delete, &mut Vec::new()).await.unwrap(); + let heads: i64=sqlx::query_scalar("SELECT count(*) FROM events WHERE community_id=$1 AND channel_id=$2 AND kind IN (39000,39001,39002) AND deleted_at IS NULL") + .bind(f.other).bind(deleted).fetch_one(&f.pool).await.unwrap(); + assert_eq!(heads, 0); +} diff --git a/crates/buzz-db/src/store/user_deletion/account_batches/mod.rs b/crates/buzz-db/src/store/user_deletion/account_batches/mod.rs new file mode 100644 index 0000000000..2cc6ffc61d --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/account_batches/mod.rs @@ -0,0 +1,451 @@ +//! Bounded account-table cleanup for one community, shared by CLI and workflow. +//! Deletion assumes relay and external writers are stopped. + +use super::{normalize_user_deletion_pubkey, ExecutionMode, UserDeletionStore}; +use crate::{DbError, Result}; +use serde::Serialize; +use serde_json::{json, Value}; +use sqlx::PgConnection; +use std::io::Write; +use uuid::Uuid; + +mod community_memberships; +mod memberships; +mod operations; +mod ownership; +mod scope; +use operations::{Operation, GLOBAL_OPERATIONS, OPERATIONS}; +pub use scope::{AccountCommunityScope, AccountScope}; + +#[cfg(test)] +mod postgres_tests; + +/// Scope and output bounds for the offline account command. +pub struct AccountBatchOptions { + /// Exactly one externally selected surviving community. + pub community: Uuid, + /// Human public key, hex or npub. Normalized before any query. + pub pubkey: String, + /// Maximum rows per transaction, 1..=100. + pub batch_size: u16, + /// Maximum row operations in one invocation, 1..=1,000,000. + pub max_items: u32, +} + +/// Explicit deployment-wide cleanup; never implied by a community invocation. +pub struct GlobalAccountBatchOptions { + /// Exactly one human or agent key, hex or npub. + pub pubkey: String, + /// Operator performing the offline action, recorded for role revocations. + pub actor: String, + /// Maximum rows per transaction, 1..=100. + pub batch_size: u16, + /// Maximum row operations per invocation, 1..=1,000,000. + pub max_items: u32, +} + +struct Options { + target: String, + agents: Vec, + community: Option, + pubkey: String, + actor: Option, + batch_size: u16, + max_items: u32, +} + +impl Options { + fn scope_sql(&self) -> &'static str { + if self.community.is_some() { + "community_id=$1" + } else { + "$1::uuid IS NULL" + } + } +} + +/// Outcome limited to the explicitly supported account-table operations. +#[derive(Debug, Serialize)] +pub struct AccountBatchSummary { + record: &'static str, + /// True only in print-only mode. + pub read_only: bool, + /// Proposed row operations in preview; committed operations in delete mode. + pub items: u32, + /// Number of nonempty batches printed or committed. + pub batches: u32, + /// False if the invocation limit stopped before all supported operations. + pub supported_scope_exhausted: bool, + /// Always false: profile, shared-state, device and access verification remain. + pub account_erasure_complete: bool, +} + +impl UserDeletionStore { + /// Clean global listeners, feedback and DB roles for one explicitly selected + /// key. The caller supplies the audit actor. No workflow stage can imply this + /// deployment-wide authority. Config-backed roles must be removed separately. + pub async fn run_global_account_batches( + &self, + options: &GlobalAccountBatchOptions, + mode: ExecutionMode, + writer: &mut impl Write, + ) -> Result { + let options = Options { + target: normalize_user_deletion_pubkey(&options.pubkey)?, + agents: Vec::new(), + community: None, + pubkey: normalize_user_deletion_pubkey(&options.pubkey)?, + actor: Some(normalize_user_deletion_pubkey(&options.actor)?), + batch_size: options.batch_size, + max_items: options.max_items, + }; + bounds(options.batch_size, options.max_items)?; + self.run_batches(&options, GLOBAL_OPERATIONS, mode, writer, None) + .await + } + + async fn run_batches( + &self, + options: &Options, + operations: &[Operation], + mode: ExecutionMode, + writer: &mut impl Write, + stage: Option<(&crate::entity_deletion::EntityLease, Uuid)>, + ) -> Result { + let delete = mode == ExecutionMode::Delete; + let mut summary = AccountBatchSummary { + record: "account_batches_summary", + read_only: !delete, + items: 0, + batches: 0, + supported_scope_exhausted: true, + account_erasure_complete: false, + }; + if delete { + let mut start_tx = self.pool.begin().await?; + timeouts(&mut start_tx).await?; + start(&mut start_tx, options, writer, true).await?; + start_tx.commit().await?; + for op in operations { + if op.table == "channel_members" && op.action == "delete" { + self.delete_memberships(options, op, writer, stage, &mut summary) + .await?; + if !summary.supported_scope_exhausted { + break; + } + continue; + } + if op.table == "relay_members" && op.action == "delete" { + self.delete_community_membership(options, op, writer, stage, &mut summary) + .await?; + if !summary.supported_scope_exhausted { + break; + } + continue; + } + loop { + let mut tx = self.pool.begin().await?; + timeouts(&mut tx).await?; + if let Some((lease, id)) = stage { + validate_stage(&mut tx, lease, id, options).await?; + } + ownership::recheck(&mut tx, options, true).await?; + if op.table == "relay_operators" { + crate::store::relay_operators::acquire_roster_lock(&mut tx).await?; + } + let keys = select(&mut tx, options, op, None, true, &summary).await?; + if keys.is_empty() { + tx.commit().await?; + break; + } + if summary.items == options.max_items { + summary.supported_scope_exhausted = false; + tx.rollback().await?; + break; + } + batch(writer, options, op, &keys, &summary)?; + mutate(&mut tx, options, op, &keys).await?; + if let Some((lease, id)) = stage { + validate_stage(&mut tx, lease, id, options).await?; + } + tx.commit().await?; + summary.items += keys.len() as u32; + summary.batches += 1; + line( + writer, + &json!({"record":"batch_committed", "number":summary.batches, + "table":op.table,"action":op.action,"items":keys.len()}), + )?; + } + if !summary.supported_scope_exhausted { + break; + } + } + // Independent absence checks; never infer completion from counters. + if summary.supported_scope_exhausted { + let mut verify_tx = self.pool.begin().await?; + timeouts(&mut verify_tx).await?; + for op in operations { + if !select(&mut verify_tx, options, op, None, false, &summary) + .await? + .is_empty() + { + return Err(invalid("supported rows remain; rerun to resume")); + } + } + verify_tx.commit().await?; + } + } else { + let mut tx = self.pool.begin().await?; + timeouts(&mut tx).await?; + sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY") + .execute(&mut *tx) + .await?; + ownership::recheck(&mut tx, options, false).await?; + start(&mut tx, options, writer, false).await?; + for op in operations { + let mut cursor = None; + loop { + let keys = + select(&mut tx, options, op, cursor.as_ref(), false, &summary).await?; + if keys.is_empty() { + break; + } + if summary.items == options.max_items { + summary.supported_scope_exhausted = false; + break; + } + batch(writer, options, op, &keys, &summary)?; + cursor = keys.last().cloned(); + summary.items += keys.len() as u32; + summary.batches += 1; + } + if !summary.supported_scope_exhausted { + break; + } + } + tx.commit().await?; + } + line(writer, &summary)?; + Ok(summary) + } +} + +fn bounds(batch_size: u16, max_items: u32) -> Result<()> { + if !(1..=100).contains(&batch_size) || !(1..=1_000_000).contains(&max_items) { + return Err(invalid( + "batch-size must be 1..100 and max-items 1..1000000", + )); + } + Ok(()) +} + +fn validated(options: &AccountBatchOptions) -> Result { + bounds(options.batch_size, options.max_items)?; + Ok(Options { + target: normalize_user_deletion_pubkey(&options.pubkey)?, + agents: Vec::new(), + community: Some(options.community), + actor: None, + pubkey: normalize_user_deletion_pubkey(&options.pubkey)?, + batch_size: options.batch_size, + max_items: options.max_items, + }) +} + +async fn start( + conn: &mut PgConnection, + options: &Options, + writer: &mut impl Write, + delete: bool, +) -> Result<()> { + if let Some(community) = options.community { + let exists: bool = + sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM communities WHERE id=$1)") + .bind(community) + .fetch_one(&mut *conn) + .await?; + if !exists { + return Err(invalid("community does not exist")); + } + } + let (archives, watermarks): (i64,i64) = sqlx::query_as( + "SELECT (SELECT count(*) FROM archived_identities WHERE community_id=$1 AND (pubkey=$2 OR actor=$2)), + (SELECT count(*) FROM parameterized_event_watermarks WHERE community_id=$1 AND pubkey=decode($2,'hex'))") + .bind(options.community).bind(&options.pubkey).fetch_one(conn).await?; + line( + writer, + &json!({"record":"account_batches_start","read_only":!delete,"community":options.community, + "pubkey":options.pubkey,"batch_size":options.batch_size,"max_items":options.max_items, + "scope":if options.community.is_some() {"community"} else {"deployment_global"}, + "actor":options.actor, + "deferred":{"archived_identities":archives}, + "retained":{"parameterized_event_watermarks":watermarks, + "policy":["replay protection and deletion evidence","shared creator and repository routing references", + "moderation, enforcement and audit history","shared or uncertain device registrations", + "historical superseded signed membership snapshots"]}, + "unsupported":["profile cleanup","remaining workflow handlers", + "device ownership attribution", + "repository and config-backed authority revocation","cache and live-session invalidation"], + "account_erasure_complete":false}), + ) +} + +async fn select( + conn: &mut PgConnection, + options: &Options, + op: &Operation, + cursor: Option<&Value>, + lock: bool, + summary: &AccountBatchSummary, +) -> Result> { + let batch_size = if op.table == "channel_members" && op.action == "delete" { + 1 + } else { + options.batch_size + }; + let limit = u32::from(batch_size).min(options.max_items.saturating_sub(summary.items).max(1)); + let lock = if lock { " FOR UPDATE" } else { "" }; + let (order, after) = op.pagination(); + let sql = format!("SELECT {} FROM {} WHERE {} AND ({}) AND ($3::jsonb IS NULL OR {after}) ORDER BY {order} LIMIT $4{lock}", op.key, op.table, options.scope_sql(), op.selector); + // All interpolated fragments come exclusively from OPERATIONS. + Ok(sqlx::query_scalar(sqlx::AssertSqlSafe(sql)) + .bind(options.community) + .bind(&options.pubkey) + .bind(cursor) + .bind(i64::from(limit)) + .fetch_all(conn) + .await?) +} + +async fn mutate( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + options: &Options, + op: &Operation, + keys: &[Value], +) -> Result<()> { + if op.table == "relay_operators" { + let target = hex::decode(&options.pubkey).map_err(|_| invalid("invalid target"))?; + let actor = hex::decode( + options + .actor + .as_deref() + .ok_or_else(|| invalid("missing audit actor"))?, + ) + .map_err(|_| invalid("invalid actor"))?; + // Conservatively require a surviving DB operator: local CLI environment + // is not evidence of the configuration on every serving relay. + if !crate::store::relay_operators::remove_in_transaction(tx, &target, &actor, false).await? + { + return Err(invalid("selected role changed; current batch rolled back")); + } + return Ok(()); + } + let conn = &mut **tx; + if op.table == "events" { + // Migration-created NIP-RS guard requires this supported opt-in. The + // desired-state schema no longer installs the legacy guard. + sqlx::query("SELECT set_config('buzz.nip_rs_hard_delete','on',true)") + .execute(&mut *conn) + .await?; + } + let verb = match op.update { + Some(update) => update.to_owned(), + None => format!("DELETE FROM {}", op.table), + }; + let sql = format!( + "{verb} WHERE {} AND ({}) AND ({})", + options.scope_sql(), + op.selector, + op.identity + ); + for key in keys { + let changed = sqlx::query(sqlx::AssertSqlSafe(sql.clone())) + .bind(options.community) + .bind(&options.pubkey) + .bind(key) + .execute(&mut *conn) + .await? + .rows_affected(); + if changed != 1 { + return Err(invalid("selected row changed; current batch rolled back")); + } + } + Ok(()) +} + +fn batch( + writer: &mut impl Write, + options: &Options, + op: &Operation, + keys: &[Value], + summary: &AccountBatchSummary, +) -> Result<()> { + line( + writer, + &json!({"record":"proposed_batch","number":summary.batches+1,"community":options.community, + "table":op.table,"action":op.action,"keys":keys, + "rebuild_saved_channel_lists":op.table == "channel_members" && op.action == "delete"}), + ) +} + +fn invalid(message: impl Into) -> 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() > 256 * 1024 { + return Err(invalid("batch output exceeds 256 KiB; reduce batch-size")); + } + writer + .write_all(&bytes) + .and_then(|()| writer.write_all(b"\n")) + .and_then(|()| writer.flush()) + .map_err(|error| invalid(format!("batch output failed: {error}"))) +} + +async fn validate_stage( + tx: &mut PgConnection, + lease: &crate::entity_deletion::EntityLease, + stage_id: Uuid, + options: &Options, +) -> Result<()> { + use crate::store::entity_deletion::{lock_owned, validate_approved_inventory}; + let request = lock_owned(tx, lease).await?; + validate_approved_inventory(tx, &request).await?; + let inputs = + super::UserDeletionInventory::read(&request)?.inputs(&request.target, options.community)?; + if request.status != "running" + || normalize_user_deletion_pubkey(&request.target)? != options.target + { + return Err(invalid("account stage target or status changed")); + } + let matches: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM entity_deletion_stage_history + WHERE id=$1 AND request_id=$2 AND stage='purge_account' AND is_current + AND status='running' AND target_community_id=$3 AND metadata_json->'inputs'=$4)", + ) + .bind(stage_id) + .bind(lease.request_id) + .bind(options.community) + .bind(inputs) + .fetch_one(&mut *tx) + .await?; + if !matches { + return Err(invalid( + "account stage is not current or outside approved scope", + )); + } + Ok(()) +} + +async fn timeouts(conn: &mut PgConnection) -> Result<()> { + sqlx::query("SET LOCAL statement_timeout='30s'") + .execute(&mut *conn) + .await?; + sqlx::query("SET LOCAL lock_timeout='3s'") + .execute(conn) + .await?; + Ok(()) +} diff --git a/crates/buzz-db/src/store/user_deletion/account_batches/operations.rs b/crates/buzz-db/src/store/user_deletion/account_batches/operations.rs new file mode 100644 index 0000000000..403a77795f --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/account_batches/operations.rs @@ -0,0 +1,145 @@ +//! Closed SQL vocabulary: caller input is always bound, never interpolated. + +pub(super) struct Operation { + pub table: &'static str, + pub action: &'static str, + pub selector: &'static str, + pub key: &'static str, + pub identity: &'static str, + // Complete literal UPDATE prefixes keep the table and SET list auditable. + pub update: Option<&'static str>, +} + +impl Operation { + // Native primary-key ordering lets PostgreSQL page without sorting JSON + // representations of every remaining key on every batch. + pub(super) fn pagination(&self) -> (&'static str, &'static str) { + match self.table { + "api_tokens" | "relay_invites" | "product_feedback" | "push_wake_outbox" | "operator_listener_outbox" => ("id", "id>($3->>'id')::uuid"), + "events" => ("created_at,id", "(created_at,id)>(($3->>'created_at')::timestamptz,decode($3->>'id','hex'))"), + "event_mentions" => ("pubkey_hex,event_id", "(pubkey_hex,event_id)>($3->>'pubkey_hex',decode($3->>'event_id','hex'))"), + "push_match_queue" => ("event_id", "event_id>decode($3->>'event_id','hex')"), + "delivery_log" => ("delivered_at,id", "(delivered_at,id)>(($3->>'delivered_at')::timestamptz,($3->>'id')::bigint)"), + "operator_listener_pubkeys" => ("listener_pubkey,target_pubkey", "(listener_pubkey,target_pubkey)>(decode($3->>'listener_pubkey','hex'),decode($3->>'target_pubkey','hex'))"), + "channel_members" => ("channel_id,pubkey", "(channel_id,pubkey)>(($3->>'channel_id')::uuid,decode($3->>'pubkey','hex'))"), + "join_policy_acceptances" => ("pubkey,policy_version", "(pubkey,policy_version)>($3->>'pubkey',$3->>'policy_version')"), + "pubkey_allowlist" | "relay_operators" => ("pubkey", "pubkey>decode($3->>'pubkey','hex')"), + "personal_read_frontiers" => ("actor,channel_id,root_id", "(actor,channel_id,root_id)>(decode($3->>'actor','hex'),($3->>'channel_id')::uuid,decode($3->>'root_id','hex'))"), + "personal_read_accounts" => ("actor", "actor>decode($3->>'actor','hex')"), + // The only remaining operations have a text pubkey primary key. + _ => ("pubkey", "pubkey>$3->>'pubkey'"), + } + } +} + +const ID_KEY: &str = "jsonb_build_object('id',id)"; +const ID_MATCH: &str = "id=($3->>'id')::uuid"; +const BYTE_KEY: &str = "jsonb_build_object('pubkey',encode(pubkey,'hex'))"; +const BYTE_MATCH: &str = "pubkey=decode($3->>'pubkey','hex')"; +const TEXT_KEY: &str = "jsonb_build_object('pubkey',pubkey)"; +const TEXT_MATCH: &str = "pubkey=$3->>'pubkey'"; +const MEMBER_KEY: &str = + "jsonb_build_object('channel_id',channel_id,'pubkey',encode(pubkey,'hex'))"; +const MEMBER_MATCH: &str = + "channel_id=($3->>'channel_id')::uuid AND pubkey=decode($3->>'pubkey','hex')"; + +const fn delete( + table: &'static str, + selector: &'static str, + key: &'static str, + identity: &'static str, +) -> Operation { + Operation { + table, + action: "delete", + selector, + key, + identity, + update: None, + } +} + +const fn clear( + table: &'static str, + action: &'static str, + selector: &'static str, + key: &'static str, + identity: &'static str, + update: &'static str, +) -> Operation { + Operation { + table, + action, + selector, + key, + identity, + update: Some(update), + } +} + +// Only directly authored personal-state kinds. Shared emoji sets/entries, +// profile events, DM commands and relay-signed membership snapshots are not +// personal settings. Include soft-deleted revisions: they still hold payloads. +macro_rules! personal_events { + () => { "pubkey=decode($2,'hex') AND kind IN (3,10000,10001,10002,10003,10030,30000,30003,30315,30078)" }; +} +macro_rules! personal_event_copy { + () => { + concat!( + "event_id IN (SELECT id FROM events WHERE community_id=$1 AND ", + personal_events!(), + ")" + ) + }; +} + +// Children before parents. Memberships include removed rows; credentials include +// expired/revoked rows. Nullable provenance updates never remove another owner. +pub(super) const OPERATIONS: &[Operation] = &[ + delete("product_feedback", "submitter_pubkey=decode($2,'hex')", ID_KEY, ID_MATCH), + delete("api_tokens", "owner_pubkey=decode($2,'hex')", ID_KEY, ID_MATCH), + delete("relay_invites", "created_by=$2", ID_KEY, ID_MATCH), + delete("channel_members", "pubkey=decode($2,'hex')", MEMBER_KEY, MEMBER_MATCH), + delete("join_policy_acceptances", "pubkey=$2", + "jsonb_build_object('pubkey',pubkey,'policy_version',policy_version)", + "pubkey=$3->>'pubkey' AND policy_version=$3->>'policy_version'"), + delete("relay_members", "pubkey=$2", TEXT_KEY, TEXT_MATCH), + delete("pubkey_allowlist", "pubkey=decode($2,'hex')", BYTE_KEY, BYTE_MATCH), + delete("personal_read_frontiers", "actor=decode($2,'hex')", + "jsonb_build_object('actor',encode(actor,'hex'),'channel_id',channel_id,'root_id',encode(root_id,'hex'))", + "actor=decode($3->>'actor','hex') AND channel_id=($3->>'channel_id')::uuid AND root_id=decode($3->>'root_id','hex')"), + delete("personal_read_accounts", "actor=decode($2,'hex')", + "jsonb_build_object('actor',encode(actor,'hex'))", "actor=decode($3->>'actor','hex')"), + clear("api_tokens", "clear_revoked_by", "revoked_by=decode($2,'hex') AND owner_pubkey<>decode($2,'hex')", ID_KEY, ID_MATCH, "UPDATE api_tokens SET revoked_by=NULL"), + clear("channel_members", "clear_invited_by", "invited_by=decode($2,'hex') AND pubkey<>decode($2,'hex')", MEMBER_KEY, MEMBER_MATCH, + "UPDATE channel_members SET invited_by=NULL,sync_modified_at=clock_timestamp()"), + clear("channel_members", "clear_removed_by", "removed_by=decode($2,'hex') AND pubkey<>decode($2,'hex')", MEMBER_KEY, MEMBER_MATCH, + "UPDATE channel_members SET removed_by=NULL,sync_modified_at=clock_timestamp()"), + clear("relay_members", "clear_added_by", "added_by=$2 AND pubkey<>$2", TEXT_KEY, TEXT_MATCH, + "UPDATE relay_members SET added_by=NULL,updated_at=clock_timestamp()"), + clear("pubkey_allowlist", "clear_added_by", "added_by=decode($2,'hex') AND pubkey<>decode($2,'hex')", BYTE_KEY, BYTE_MATCH, "UPDATE pubkey_allowlist SET added_by=NULL"), + clear("archived_identities", "clear_replaced_by", "replaced_by=$2", TEXT_KEY, TEXT_MATCH, "UPDATE archived_identities SET replaced_by=NULL"), + // Copies before their source, so interruption never loses attribution. + delete("event_mentions", personal_event_copy!(), + "jsonb_build_object('pubkey_hex',pubkey_hex,'event_id',encode(event_id,'hex'))", + "pubkey_hex=$3->>'pubkey_hex' AND event_id=decode($3->>'event_id','hex')"), + delete("push_match_queue", personal_event_copy!(), + "jsonb_build_object('event_id',encode(event_id,'hex'))", "event_id=decode($3->>'event_id','hex')"), + delete("push_wake_outbox", personal_event_copy!(), ID_KEY, ID_MATCH), + delete("operator_listener_outbox", personal_event_copy!(), ID_KEY, ID_MATCH), + delete("delivery_log", personal_event_copy!(), + "jsonb_build_object('delivered_at',delivered_at,'id',id)", + "delivered_at=($3->>'delivered_at')::timestamptz AND id=($3->>'id')::bigint"), + delete("events", personal_events!(), + "jsonb_build_object('created_at',created_at,'id',encode(id,'hex'))", + "created_at=($3->>'created_at')::timestamptz AND id=decode($3->>'id','hex')"), +]; + +// No community invocation ever executes these deployment-global selectors. +pub(super) const GLOBAL_OPERATIONS: &[Operation] = &[ + delete("relay_operators", "pubkey=decode($2,'hex')", BYTE_KEY, BYTE_MATCH), + delete("operator_listener_pubkeys", "listener_pubkey=decode($2,'hex') OR target_pubkey=decode($2,'hex')", + "jsonb_build_object('listener_pubkey',encode(listener_pubkey,'hex'),'target_pubkey',encode(target_pubkey,'hex'))", + "listener_pubkey=decode($3->>'listener_pubkey','hex') AND target_pubkey=decode($3->>'target_pubkey','hex')"), + delete("product_feedback", "submitter_pubkey=decode($2,'hex')", ID_KEY, ID_MATCH), +]; 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 new file mode 100644 index 0000000000..df84e2ed43 --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/account_batches/ownership.rs @@ -0,0 +1,105 @@ +//! 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. + /// Workflow callers supply the human's current lease and stage. + pub async fn run_account_batches( + &self, + options: &AccountBatchOptions, + mode: ExecutionMode, + writer: &mut impl Write, + stage: Option<(&crate::entity_deletion::EntityLease, Uuid)>, + ) -> Result { + let mut current = validated(options)?; + let mut tx = self.pool.begin().await?; + timeouts(&mut tx).await?; + current.agents = agents(&mut tx, options.community, ¤t.target, false).await?; + tx.rollback().await?; + let keys: Vec = std::iter::once(current.target.clone()) + .chain(current.agents.iter().cloned()) + .collect(); + if mode == ExecutionMode::Delete { + self.preflight_memberships(options.community, &keys).await?; + } + let owned: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM relay_members WHERE community_id=$1 AND pubkey=ANY($2) AND role='owner')") + .bind(options.community).bind(&keys).fetch_one(&self.pool).await?; + if owned { + return Err(invalid( + "owned-community handoff required; account handler was not executed", + )); + } + line( + writer, + &json!({"record":"account_targets", "community":options.community, + "target":current.target, "agent_count":current.agents.len(), "read_only":mode == ExecutionMode::ReadOnly}), + )?; + let mut total = AccountBatchSummary { + record: "account_handler_summary", + read_only: mode == ExecutionMode::ReadOnly, + items: 0, + batches: 0, + supported_scope_exhausted: true, + account_erasure_complete: false, + }; + for key in keys { + if total.items == options.max_items || !total.supported_scope_exhausted { + total.supported_scope_exhausted = false; + break; + } + current.pubkey = key; + current.max_items = options.max_items - total.items; + let result = self + .run_batches(¤t, OPERATIONS, mode, writer, stage) + .await?; + total.items += result.items; + total.batches += result.batches; + total.supported_scope_exhausted = result.supported_scope_exhausted; + } + // Include additions as well as transfers away: a changed set requires a + // retry, which discovers it afresh. Never claim those agents were cleaned. + let mut tx = self.pool.begin().await?; + timeouts(&mut tx).await?; + recheck(&mut tx, ¤t, false).await?; + tx.rollback().await?; + line(writer, &total)?; + Ok(total) + } +} + +pub(super) async fn agents( + conn: &mut PgConnection, + community: Uuid, + 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) +} + +pub(super) async fn recheck(conn: &mut PgConnection, options: &Options, lock: bool) -> Result<()> { + if let Some(community) = options.community { + if agents(conn, community, &options.target, lock).await? != options.agents { + return Err(invalid( + "agent ownership changed; rerun the handler to fetch current agents", + )); + } + } + Ok(()) +} diff --git a/crates/buzz-db/src/store/user_deletion/account_batches/ownership_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/account_batches/ownership_postgres_tests.rs new file mode 100644 index 0000000000..643c1cc7da --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/account_batches/ownership_postgres_tests.rs @@ -0,0 +1,94 @@ +use super::{failures_postgres_tests::RecordWriter, *}; + +const AGENT: &str = "2222222222222222222222222222222222222222222222222222222222222222"; +const OTHER_OWNER: &str = "3333333333333333333333333333333333333333333333333333333333333333"; + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires Postgres"] +async fn ownership_changes_stop_batches_and_retry_fetches_current_agents() { + let mut f = Fixture::new().await; + // Missing ownership, transferred ownership, and newly assigned ownership + // all invalidate a running handler's set. No old key list is sufficient. + for (initial, next, after_table) in [ + (Some(TARGET), None, "api_tokens"), + (Some(TARGET), Some(OTHER_OWNER), "relay_invites"), + (None, Some(TARGET), "api_tokens"), + ] { + sqlx::query("UPDATE users SET agent_owner_pubkey=decode($1,'hex') WHERE community_id=$2 AND pubkey=decode($3,'hex')") + .bind(initial).bind(f.options.community).bind(AGENT).execute(&f.pool).await.unwrap(); + // Preview invokes discovery too and leaves every table untouched. + let before = f.snapshot().await; + let mut preview = Vec::new(); + f.run(ExecutionMode::ReadOnly, &mut preview).await.unwrap(); + assert_eq!(f.snapshot().await, before); + let targets = records(&preview) + .into_iter() + .find(|r| r["record"] == "account_targets") + .unwrap(); + assert_eq!(targets["agent_count"], usize::from(initial == Some(TARGET))); + + // Refill the human's first operations so the change happens between + // real committed batches, including immediately before memberships. + sqlx::query("INSERT INTO api_tokens(community_id,id,owner_pubkey,token_hash,name,scopes) VALUES ($1,gen_random_uuid(),decode($2,'hex'),decode(repeat(md5(random()::text),2),'hex'),'ownership test','[]')") + .bind(f.options.community).bind(TARGET).execute(&f.pool).await.unwrap(); + let mut changed = false; + let mut writer = RecordWriter::new(|r: &Value| { + if !changed && r["record"] == "batch_committed" && r["table"] == after_table { + tokio::task::block_in_place(|| { + tokio::runtime::Handle::current().block_on(async { + sqlx::query("UPDATE users SET agent_owner_pubkey=decode($1,'hex') WHERE community_id=$2 AND pubkey=decode($3,'hex')") + .bind(next).bind(f.options.community).bind(AGENT).execute(&f.pool).await.unwrap(); + }) + }); + changed = true; + } + Ok(()) + }); + let error = f.run(ExecutionMode::Delete, &mut writer).await.unwrap_err(); + assert!(changed); + assert!(error.to_string().contains("agent ownership changed")); + let remaining: i64 = sqlx::query_scalar( + "SELECT count(*) FROM api_tokens WHERE owner_pubkey=decode($1,'hex')", + ) + .bind(AGENT) + .fetch_one(&f.pool) + .await + .unwrap(); + assert_eq!(remaining, 6, "agent rows survive the invalidated run"); + } + // Retry picks up the addition, cleans only this community, and leaves the + // ownership source available for later handlers and further retries. + f.run(ExecutionMode::Delete, &mut Vec::new()).await.unwrap(); + let remaining: Vec = sqlx::query_scalar( + "SELECT community_id FROM api_tokens WHERE owner_pubkey=decode($1,'hex')", + ) + .bind(AGENT) + .fetch_all(&f.pool) + .await + .unwrap(); + assert_eq!(remaining, vec![f.other; 3]); + let owner: String = sqlx::query_scalar("SELECT encode(agent_owner_pubkey,'hex') FROM users WHERE community_id=$1 AND pubkey=decode($2,'hex')") + .bind(f.options.community).bind(AGENT).fetch_one(&f.pool).await.unwrap(); + assert_eq!(owner, TARGET); + assert_eq!( + f.run(ExecutionMode::Delete, &mut Vec::new()) + .await + .unwrap() + .items, + 0 + ); + // Large valid discovery sets must not exceed a single JSON record's bound. + // A small row budget still permits preview and deletion with 4,001 agents. + 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(1,4000) n") + .bind(f.options.community).bind(TARGET).execute(&f.pool).await.unwrap(); + sqlx::query("INSERT INTO api_tokens(community_id,id,owner_pubkey,token_hash,name,scopes) SELECT $1,gen_random_uuid(),decode($2,'hex'),decode(repeat(md5(random()::text),2),'hex'),'large discovery','[]' FROM generate_series(1,2)") + .bind(f.options.community).bind(TARGET).execute(&f.pool).await.unwrap(); + f.options.max_items = 1; + for mode in [ExecutionMode::ReadOnly, ExecutionMode::Delete] { + let mut output = Vec::new(); + let summary = f.run(mode, &mut output).await.unwrap(); + assert_eq!(summary.items, 1); + assert!(!summary.supported_scope_exhausted); + assert_eq!(records(&output)[0]["agent_count"], 4001); + } +} diff --git a/crates/buzz-db/src/store/user_deletion/account_batches/postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/account_batches/postgres_tests.rs new file mode 100644 index 0000000000..840e8bad7c --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/account_batches/postgres_tests.rs @@ -0,0 +1,276 @@ +use super::*; +use crate::Db; +use sqlx::PgPool; +use std::collections::BTreeSet; + +#[path = "postgres_tests/failures.rs"] +mod failures_postgres_tests; +#[path = "postgres_tests/stage.rs"] +mod stage_postgres_tests; + +#[path = "postgres_tests/expansion_postgres_tests.rs"] +mod expansion_postgres_tests; + +#[path = "memberships_postgres_tests.rs"] +mod memberships_postgres_tests; + +#[path = "community_memberships_postgres_tests.rs"] +mod community_memberships_postgres_tests; + +#[path = "ownership_postgres_tests.rs"] +mod ownership_postgres_tests; + +const TARGET: &str = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; +const TABLES: &[&str] = &[ + "api_tokens", + "relay_invites", + "channel_members", + "join_policy_acceptances", + "relay_members", + "pubkey_allowlist", + "personal_read_frontiers", + "personal_read_accounts", + "archived_identities", + "parameterized_event_watermarks", + "users", + "channels", + "entity_deletion_requests", + "entity_deletion_stage_history", + "entity_deletion_approvals", + "user_deletion_fences", +]; + +struct Fixture { + pool: PgPool, + options: AccountBatchOptions, + other: Uuid, +} + +impl Fixture { + async fn new() -> Self { + let pool = PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + let community = Uuid::new_v4(); + let other = Uuid::new_v4(); + let seed = include_str!("fixture.sql") + .replace("__TARGET__", TARGET) + .replace("__COMMUNITY__", &community.to_string()) + .replace("__OTHER__", &other.to_string()); + sqlx::raw_sql(sqlx::AssertSqlSafe(seed)) + .execute(&pool) + .await + .unwrap(); + Self { + pool, + other, + options: AccountBatchOptions { + community, + pubkey: TARGET.to_owned(), + batch_size: 2, + max_items: 1000, + }, + } + } + + fn store(&self) -> UserDeletionStore { + Db::from_pool(self.pool.clone()) + .user_deletion_store() + .with_account_snapshot_signer(nostr::Keys::parse(&format!("{:064x}", 1)).unwrap()) + } + + async fn run(&self, mode: ExecutionMode, out: &mut impl Write) -> Result { + self.store() + .run_account_batches(&self.options, mode, out, None) + .await + } + + async fn snapshot(&self) -> Value { + let mut snapshot = serde_json::Map::new(); + for table in TABLES { + let sql = format!("SELECT COALESCE(jsonb_agg(to_jsonb(r) ORDER BY to_jsonb(r)), '[]'::jsonb) FROM {table} r"); + let rows: Value = sqlx::query_scalar(sqlx::AssertSqlSafe(sql)) + .fetch_one(&self.pool) + .await + .unwrap(); + snapshot.insert((*table).to_owned(), rows); + } + Value::Object(snapshot) + } + + async fn assert_cleaned(&self, before: &Value, communities: &[Uuid]) { + let mut expected = before.clone(); + let mut actual = self.snapshot().await; + for table in TABLES { + // Independent outcome oracle: ownership removes a row; attribution + // only loses that value. All other columns and tables must survive. + let owner = match *table { + "api_tokens" => Some("owner_pubkey"), + "relay_invites" => Some("created_by"), + "channel_members" + | "join_policy_acceptances" + | "relay_members" + | "pubkey_allowlist" => Some("pubkey"), + "personal_read_frontiers" | "personal_read_accounts" => Some("actor"), + _ => None, + }; + let fields: &[&str] = match *table { + "api_tokens" => &["revoked_by"], + "channel_members" => &["invited_by", "removed_by"], + "relay_members" | "pubkey_allowlist" => &["added_by"], + "archived_identities" => &["replaced_by"], + _ => &[], + }; + let in_scope = |row: &Value| { + communities + .iter() + .any(|id| row["community_id"] == id.to_string()) + }; + let subject = |v: &Value| v == TARGET || *v == format!("\\x{TARGET}"); + let rows = expected[*table].as_array_mut().unwrap(); + rows.retain(|row| !(in_scope(row) && owner.is_some_and(|key| subject(&row[key])))); + for row in rows.iter_mut().filter(|row| in_scope(row)) { + let mut changed = false; + for key in fields { + if subject(&row[*key]) { + row[*key] = Value::Null; + changed = true; + } + } + if changed && matches!(*table, "channel_members" | "relay_members") { + let timestamp = if *table == "channel_members" { + "sync_modified_at" + } else { + "updated_at" + }; + let retained = actual[*table] + .as_array_mut() + .unwrap() + .iter_mut() + .find(|r| { + r["community_id"] == row["community_id"] + && r["pubkey"] == row["pubkey"] + && r["channel_id"] == row["channel_id"] + }) + .unwrap(); + assert!( + retained[timestamp].as_str().unwrap() > row[timestamp].as_str().unwrap() + ); + retained.as_object_mut().unwrap().remove(timestamp); + row.as_object_mut().unwrap().remove(timestamp); + } + } + rows.sort_by_key(Value::to_string); + actual[*table] + .as_array_mut() + .unwrap() + .sort_by_key(Value::to_string); + } + assert_eq!(actual, 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 all_operations_preview_paginate_delete_and_preserve_other_scopes() { + let mut f = Fixture::new().await; + let before = f.snapshot().await; + let mut output = Vec::new(); + let summary = f.run(ExecutionMode::ReadOnly, &mut output).await.unwrap(); + assert!(summary.read_only && summary.supported_scope_exhausted); + assert!(!summary.account_erasure_complete); + // 24 owned rows plus 11 nullable attribution operations. + assert_eq!(summary.items, 35); + let mut keys = BTreeSet::new(); + let mut actions = BTreeSet::new(); + for record in records(&output) + .into_iter() + .filter(|r| r["record"] == "proposed_batch") + { + let batch = record["keys"].as_array().unwrap(); + assert!(!batch.is_empty() && batch.len() <= 2); + actions.insert((record["table"].to_string(), record["action"].to_string())); + for key in batch { + assert!(keys.insert(( + record["table"].to_string(), + record["action"].to_string(), + key.to_string() + ))); + } + } + assert_eq!(keys.len(), 35); + assert_eq!(actions.len(), 14); + assert_eq!(f.snapshot().await, before); + let summary = f.run(ExecutionMode::Delete, &mut Vec::new()).await.unwrap(); + assert_eq!(summary.items, 35); + assert!( + !summary.read_only + && summary.supported_scope_exhausted + && !summary.account_erasure_complete + ); + f.assert_cleaned(&before, &[f.options.community]).await; + assert_eq!( + f.run(ExecutionMode::Delete, &mut Vec::new()) + .await + .unwrap() + .items, + 0 + ); + f.assert_cleaned(&before, &[f.options.community]).await; + let first = f.options.community; + f.options.community = f.other; + assert_eq!( + f.run(ExecutionMode::Delete, &mut Vec::new()) + .await + .unwrap() + .items, + 35 + ); + f.assert_cleaned(&before, &[first, f.other]).await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn cap_is_global_and_resumes_in_the_middle_of_an_operation() { + let mut f = Fixture::new().await; + let before = f.snapshot().await; + f.options.max_items = 1; + let preview = f + .run(ExecutionMode::ReadOnly, &mut Vec::new()) + .await + .unwrap(); + assert_eq!(preview.items, 1); + assert!(!preview.supported_scope_exhausted); + assert_eq!(f.snapshot().await, before); + let partial = f.run(ExecutionMode::Delete, &mut Vec::new()).await.unwrap(); + assert_eq!(partial.items, 1); + assert!(!partial.supported_scope_exhausted); + let mut expected = before.clone(); + let target_tokens = expected["api_tokens"].as_array_mut().unwrap(); + let first = target_tokens + .iter() + .filter(|r| { + r["community_id"] == f.options.community.to_string() + && r["owner_pubkey"] == format!("\\x{TARGET}") + }) + .min_by_key(|r| r["id"].as_str().unwrap()) + .unwrap()["id"] + .clone(); + target_tokens + .retain(|r| !(r["community_id"] == f.options.community.to_string() && r["id"] == first)); + assert_eq!(f.snapshot().await, expected); + // Exact remaining cap is complete, not an off-by-one incomplete result. + f.options.max_items = 34; + let rest = f.run(ExecutionMode::Delete, &mut Vec::new()).await.unwrap(); + assert_eq!(rest.items, 34); + assert!(rest.supported_scope_exhausted); + f.assert_cleaned(&before, &[f.options.community]).await; +} diff --git a/crates/buzz-db/src/store/user_deletion/account_batches/postgres_tests/expansion_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/account_batches/postgres_tests/expansion_postgres_tests.rs new file mode 100644 index 0000000000..334b5c5966 --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/account_batches/postgres_tests/expansion_postgres_tests.rs @@ -0,0 +1,466 @@ +use super::*; + +const OTHER_KEY: &str = "2222222222222222222222222222222222222222222222222222222222222222"; +const ACTOR: &str = "3333333333333333333333333333333333333333333333333333333333333333"; + +async fn snapshot(pool: &PgPool, tables: &[&str]) -> Value { + let mut result = serde_json::Map::new(); + for table in tables { + let sql = format!( + "SELECT COALESCE(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)), '[]') FROM {table} t" + ); + result.insert( + (*table).into(), + sqlx::query_scalar::<_, Value>(sqlx::AssertSqlSafe(sql)) + .fetch_one(pool) + .await + .unwrap(), + ); + } + result.into() +} + +async fn seed_feedback(f: &Fixture) { + sqlx::query("INSERT INTO product_feedback(community_id,event_id,submitter_pubkey,body,tags,event_created_at) + SELECT community,decode(md5(pubkey||COALESCE(community::text,'global'))||md5(pubkey||COALESCE(community::text,'global')),'hex'),decode(pubkey,'hex'),'private feedback','[[\"detail\",\"private\"]]',now() + FROM (VALUES ($1::uuid),($2::uuid),(NULL::uuid)) c(community) + CROSS JOIN (VALUES ($3::text),($4::text)) p(pubkey)") + .bind(f.options.community).bind(f.other).bind(TARGET).bind(OTHER_KEY).execute(&f.pool).await.unwrap(); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn global_roles_listeners_feedback_preview_audit_cap_and_retry() { + let f = Fixture::new().await; + seed_feedback(&f).await; + sqlx::query("INSERT INTO relay_operators(pubkey,role,added_by) VALUES (decode($1,'hex'),'operator',decode($2,'hex')),(decode($2,'hex'),'operator',decode($1,'hex'))") + .bind(TARGET).bind(ACTOR).execute(&f.pool).await.unwrap(); + sqlx::query("INSERT INTO operator_listener_pubkeys(listener_pubkey,target_pubkey) SELECT decode(l,'hex'),decode(t,'hex') FROM (VALUES ($1::text,$2::text),($2,$1),($2,$2)) v(l,t)") + .bind(TARGET).bind(OTHER_KEY).execute(&f.pool).await.unwrap(); + let tables = [ + "relay_operators", + "relay_operator_audit", + "operator_listener_pubkeys", + "product_feedback", + ]; + let before = snapshot(&f.pool, &tables).await; + let mut options = GlobalAccountBatchOptions { + pubkey: TARGET.into(), + actor: ACTOR.into(), + batch_size: 1, + max_items: 100, + }; + let store = f.store(); + let preview = store + .run_global_account_batches(&options, ExecutionMode::ReadOnly, &mut Vec::new()) + .await + .unwrap(); + assert_eq!(preview.items, 6); // role, both listener directions, feedback in both communities and NULL + assert_eq!(snapshot(&f.pool, &tables).await, before); + options.max_items = 1; + let first = store + .run_global_account_batches(&options, ExecutionMode::Delete, &mut Vec::new()) + .await + .unwrap(); + assert_eq!(first.items, 1); + assert!(!first.supported_scope_exhausted); + let audit: (Vec, Vec, String, String) = + sqlx::query_as("SELECT actor_pubkey,target_pubkey,op,prev_role FROM relay_operator_audit") + .fetch_one(&f.pool) + .await + .unwrap(); + assert_eq!( + audit, + ( + hex::decode(ACTOR).unwrap(), + hex::decode(TARGET).unwrap(), + "revoke".into(), + "operator".into() + ) + ); + options.max_items = 100; + assert_eq!( + store + .run_global_account_batches(&options, ExecutionMode::Delete, &mut Vec::new()) + .await + .unwrap() + .items, + 5 + ); + let after = snapshot(&f.pool, &tables).await; + for table in [ + "relay_operators", + "operator_listener_pubkeys", + "product_feedback", + ] { + let expected: Vec<_> = before[table] + .as_array() + .unwrap() + .iter() + .filter(|row| match table { + "relay_operators" => row["pubkey"] != format!("\\x{TARGET}"), + "operator_listener_pubkeys" => { + row["listener_pubkey"] != format!("\\x{TARGET}") + && row["target_pubkey"] != format!("\\x{TARGET}") + } + _ => row["submitter_pubkey"] != format!("\\x{TARGET}"), + }) + .cloned() + .collect(); + assert_eq!(after[table], json!(expected)); + } + assert_eq!( + store + .run_global_account_batches(&options, ExecutionMode::Delete, &mut Vec::new()) + .await + .unwrap() + .items, + 0 + ); + assert_eq!(snapshot(&f.pool, &tables).await, after); // retry never duplicates audit + assert_eq!( + f.snapshot().await["api_tokens"].as_array().unwrap().len(), + 18 + ); // global != all tenant records +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn global_last_operator_rolls_back_before_other_cleanup() { + let f = Fixture::new().await; + seed_feedback(&f).await; + sqlx::query("INSERT INTO relay_operators(pubkey,role,added_by) VALUES (decode($1,'hex'),'operator',decode($1,'hex'))").bind(TARGET).execute(&f.pool).await.unwrap(); + let tables = [ + "relay_operators", + "relay_operator_audit", + "product_feedback", + ]; + let before = snapshot(&f.pool, &tables).await; + let result = f + .store() + .run_global_account_batches( + &GlobalAccountBatchOptions { + pubkey: TARGET.into(), + actor: ACTOR.into(), + batch_size: 2, + max_items: 100, + }, + ExecutionMode::Delete, + &mut Vec::new(), + ) + .await; + assert!(matches!(result, Err(DbError::LastOperator))); + assert_eq!(snapshot(&f.pool, &tables).await, before); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn personal_events_revisions_copies_and_community_feedback_are_removed() { + let f = Fixture::new().await; + seed_feedback(&f).await; + // Every personal kind, plus content/profile/shared-list exclusions. Both live + // and soft-deleted versions, identical IDs across communities, another author. + sqlx::query("INSERT INTO events(community_id,id,pubkey,kind,created_at,content,tags,sig,deleted_at,d_tag) + SELECT community,decode(md5(pubkey||kind||rev)||md5(pubkey||kind||rev),'hex'),decode(pubkey,'hex'),kind, + '2026-11-01'::timestamptz + rev*interval '1 second','private setting','[[\"p\",\"private\"]]',decode(repeat('00',64),'hex'),CASE WHEN rev=1 THEN now() END,'private-coordinate' + FROM (VALUES ($1::uuid),($2::uuid)) c(community) CROSS JOIN (VALUES ($3::text),($4::text)) p(pubkey) + CROSS JOIN unnest(ARRAY[3,10000,10001,10002,10003,10030,30000,30003,30315,30078,0,9,30030,30180,39002,55555]) kind CROSS JOIN generate_series(1,2) rev") + .bind(f.options.community).bind(f.other).bind(TARGET).bind(OTHER_KEY).execute(&f.pool).await.unwrap(); + sqlx::query("INSERT INTO event_mentions(community_id,pubkey_hex,event_id,event_created_at,event_kind) SELECT community_id,$1,id,created_at,kind FROM events").bind(ACTOR).execute(&f.pool).await.unwrap(); + sqlx::query( + "INSERT INTO push_match_queue(community_id,event_id) SELECT community_id,id FROM events", + ) + .execute(&f.pool) + .await + .unwrap(); + sqlx::query("INSERT INTO operator_listener_outbox(listener_pubkey,target_pubkey,community_id,event_id,event_kind,event_created_at) SELECT decode($1,'hex'),pubkey,community_id,id,kind,created_at FROM events").bind(ACTOR).execute(&f.pool).await.unwrap(); + sqlx::query( + "INSERT INTO delivery_log(community_id,event_id) SELECT community_id,id FROM events", + ) + .execute(&f.pool) + .await + .unwrap(); + let tables = [ + "events", + "event_mentions", + "push_match_queue", + "operator_listener_outbox", + "delivery_log", + "product_feedback", + "parameterized_event_watermarks", + ]; + let before = snapshot(&f.pool, &tables).await; + let mut output = Vec::new(); + f.run(ExecutionMode::ReadOnly, &mut output).await.unwrap(); + assert_eq!(snapshot(&f.pool, &tables).await, before); + let selected: BTreeSet<_> = before["events"] + .as_array() + .unwrap() + .iter() + .filter(|r| { + r["community_id"] == f.options.community.to_string() + && r["pubkey"] == format!("\\x{TARGET}") + && [ + 3, 10000, 10001, 10002, 10003, 10030, 30000, 30003, 30315, 30078, + ] + .contains(&r["kind"].as_i64().unwrap()) + }) + .map(|r| r["id"].as_str().unwrap().to_owned()) + .collect(); + assert_eq!(selected.len(), 20); + f.run(ExecutionMode::Delete, &mut Vec::new()).await.unwrap(); + let after = snapshot(&f.pool, &tables).await; + for table in tables { + let expected: Vec<_> = before[table] + .as_array() + .unwrap() + .iter() + .filter(|r| { + let in_community = r["community_id"] == f.options.community.to_string(); + if table == "product_feedback" { + !(in_community && r["submitter_pubkey"] == format!("\\x{TARGET}")) + } else if table == "parameterized_event_watermarks" { + true + } else { + !(in_community + && r[if table == "events" { "id" } else { "event_id" }] + .as_str() + .is_some_and(|id| selected.contains(id))) + } + }) + .cloned() + .collect(); + // Membership cleanup adds signed channel and community rosters and + // their mention entries; dedicated journeys test those independently. + let generated: BTreeSet<_> = after["events"] + .as_array() + .unwrap() + .iter() + .filter(|r| { + (!r["channel_id"].is_null() + && [39000, 39001, 39002].contains(&r["kind"].as_i64().unwrap())) + || r["kind"] == 13534 + }) + .map(|r| r["id"].clone().to_string()) + .collect(); + let actual: Vec<_> = after[table] + .as_array() + .unwrap() + .iter() + .filter(|r| { + !(matches!(table, "events" | "event_mentions") + && generated.contains( + &r[if table == "events" { "id" } else { "event_id" }].to_string(), + )) + }) + .cloned() + .collect(); + assert_eq!(json!(actual), json!(expected), "{table}"); + } + assert_eq!( + f.run(ExecutionMode::Delete, &mut Vec::new()) + .await + .unwrap() + .items, + 0 + ); + assert_eq!(snapshot(&f.pool, &tables).await, after); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn scope_refreshes_ownership_on_retry_and_covers_former_communities() { + let f = Fixture::new().await; + sqlx::query("UPDATE users SET agent_owner_pubkey=decode($1,'hex') WHERE community_id=$2 AND pubkey=decode($3,'hex')").bind(TARGET).bind(f.options.community).bind(OTHER_KEY).execute(&f.pool).await.unwrap(); + sqlx::query("DELETE FROM relay_members WHERE pubkey=$1") + .bind(TARGET) + .execute(&f.pool) + .await + .unwrap(); + sqlx::query("UPDATE channel_members SET removed_at=now() WHERE pubkey=decode($1,'hex')") + .bind(TARGET) + .execute(&f.pool) + .await + .unwrap(); + let store = f.store(); + let scope = store.generate_account_scope(TARGET).await.unwrap(); + assert_eq!(scope.communities.len(), 2); + assert_eq!( + scope + .communities + .iter() + .find(|c| c.community == f.options.community) + .unwrap() + .pubkeys + .len(), + 2 + ); + assert_eq!( + scope + .communities + .iter() + .find(|c| c.community == f.other) + .unwrap() + .pubkeys + .len(), + 1 + ); + let before = f.snapshot().await; + store + .run_account_scope( + &scope, + ACTOR, + 2, + 1000, + ExecutionMode::ReadOnly, + &mut Vec::new(), + ) + .await + .unwrap(); + assert_eq!(f.snapshot().await, before); + // A saved key is not authority: transfer away after preview, then prove + // both communities preserve that agent. A later retry discovers it anew. + sqlx::query("UPDATE users SET agent_owner_pubkey=decode($1,'hex')") + .bind(ACTOR) + .execute(&f.pool) + .await + .unwrap(); + let saved: AccountScope = serde_json::from_value(serde_json::to_value(scope).unwrap()).unwrap(); + let first = store + .run_account_scope(&saved, ACTOR, 2, 1, ExecutionMode::Delete, &mut Vec::new()) + .await + .unwrap(); + assert_eq!(first.items, 1); + assert!(!first.supported_scope_exhausted); + let rest = store + .run_account_scope( + &saved, + ACTOR, + 2, + 1000, + ExecutionMode::Delete, + &mut Vec::new(), + ) + .await + .unwrap(); + assert!(rest.supported_scope_exhausted); + let retained: i64 = + sqlx::query_scalar("SELECT count(*) FROM api_tokens WHERE owner_pubkey=decode($1,'hex')") + .bind(OTHER_KEY) + .fetch_one(&f.pool) + .await + .unwrap(); + assert_eq!(retained, 6); + // Reassign only in the first community. The same file must pick this up. + sqlx::query("UPDATE users SET agent_owner_pubkey=decode($1,'hex') WHERE community_id=$2 AND pubkey=decode($3,'hex')") + .bind(TARGET).bind(f.options.community).bind(OTHER_KEY).execute(&f.pool).await.unwrap(); + store + .run_account_scope( + &saved, + ACTOR, + 2, + 1000, + ExecutionMode::Delete, + &mut Vec::new(), + ) + .await + .unwrap(); + let tokens:Vec<(Uuid,String)>=sqlx::query_as("SELECT community_id,encode(owner_pubkey,'hex') FROM api_tokens ORDER BY community_id,owner_pubkey").fetch_all(&f.pool).await.unwrap(); + assert!(tokens + .iter() + .all(|(c, k)| k != TARGET && (*c != f.options.community || k != OTHER_KEY))); + assert_eq!( + tokens + .iter() + .filter(|(c, k)| *c == f.other && k == OTHER_KEY) + .count(), + 3 + ); + assert_eq!( + store + .run_account_scope( + &saved, + ACTOR, + 2, + 1000, + ExecutionMode::Delete, + &mut Vec::new() + ) + .await + .unwrap() + .items, + 0 + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn frozen_scope_rejects_owned_community_before_global_mutation() { + let f = Fixture::new().await; + seed_feedback(&f).await; + sqlx::query("UPDATE relay_members SET role='owner' WHERE community_id=$1 AND pubkey=$2") + .bind(f.other) + .bind(TARGET) + .execute(&f.pool) + .await + .unwrap(); + let scope = f.store().generate_account_scope(TARGET).await.unwrap(); + let before = snapshot( + &f.pool, + &["product_feedback", "relay_members", "api_tokens"], + ) + .await; + let error = f + .store() + .run_account_scope( + &scope, + ACTOR, + 2, + 1000, + ExecutionMode::Delete, + &mut Vec::new(), + ) + .await + .unwrap_err(); + assert!(error.to_string().contains("owned-community handoff")); + assert_eq!( + snapshot( + &f.pool, + &["product_feedback", "relay_members", "api_tokens"] + ) + .await, + before + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn frozen_scope_without_any_community_still_cleans_global_records() { + let pool = PgPool::connect(&crate::test_support::database_url()) + .await + .unwrap(); + sqlx::query("INSERT INTO product_feedback(event_id,submitter_pubkey,body,event_created_at) VALUES (decode($1,'hex'),decode($1,'hex'),'private',now())").bind(TARGET).execute(&pool).await.unwrap(); + let store = Db::from_pool(pool.clone()).user_deletion_store(); + let scope = store.generate_account_scope(TARGET).await.unwrap(); + assert!(scope.communities.is_empty()); + let result = store + .run_account_scope( + &scope, + ACTOR, + 2, + 1000, + ExecutionMode::Delete, + &mut Vec::new(), + ) + .await + .unwrap(); + assert_eq!(result.items, 1); + assert!(result.supported_scope_exhausted && !result.account_erasure_complete); + assert_eq!( + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM product_feedback") + .fetch_one(&pool) + .await + .unwrap(), + 0 + ); +} diff --git a/crates/buzz-db/src/store/user_deletion/account_batches/postgres_tests/failures.rs b/crates/buzz-db/src/store/user_deletion/account_batches/postgres_tests/failures.rs new file mode 100644 index 0000000000..4aa4d75a79 --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/account_batches/postgres_tests/failures.rs @@ -0,0 +1,135 @@ +use super::*; +use std::{io, time::Duration}; + +pub(super) struct RecordWriter { + line: Vec, + pub callback: F, +} + +impl RecordWriter { + pub fn new(callback: F) -> Self { + Self { + line: Vec::new(), + callback, + } + } +} + +impl io::Result<()>> Write for RecordWriter { + fn write(&mut self, bytes: &[u8]) -> io::Result { + self.line.extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> io::Result<()> { + let record: Value = serde_json::from_slice(&self.line)?; + self.line.clear(); + (self.callback)(&record) + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn output_failure_before_mutation_rolls_back_but_after_commit_is_durable() { + let f = Fixture::new().await; + let before = f.snapshot().await; + for record_type in ["account_batches_start", "proposed_batch"] { + let mut writer = RecordWriter::new(|r: &Value| { + if r["record"] == record_type { + return Err(io::Error::other("injected output failure")); + } + Ok(()) + }); + let err = f.run(ExecutionMode::Delete, &mut writer).await.unwrap_err(); + assert!(err.to_string().contains("injected output failure")); + assert_eq!(f.snapshot().await, before); + } + let mut writer = RecordWriter::new(|r: &Value| { + if r["record"] == "batch_committed" { + return Err(io::Error::other("lost receipt")); + } + Ok(()) + }); + assert!(f + .run(ExecutionMode::Delete, &mut writer) + .await + .unwrap_err() + .to_string() + .contains("lost receipt")); + let after = f.snapshot().await; + assert_eq!( + after["api_tokens"].as_array().unwrap().len(), + before["api_tokens"].as_array().unwrap().len() - 2 + ); + for table in TABLES.iter().filter(|t| **t != "api_tokens") { + assert_eq!(after[*table], before[*table], "{table}"); + } + assert_eq!( + f.run(ExecutionMode::Delete, &mut Vec::new()) + .await + .unwrap() + .items, + 33 + ); + f.assert_cleaned(&before, &[f.options.community]).await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn cancellation_after_commit_preserves_batch_and_can_retry() { + let f = Fixture::new().await; + let before = f.snapshot().await; + let mut blocker = f.pool.begin().await.unwrap(); + // Hold the third token, so batch one commits and batch two cannot complete. + // OFFSET with FOR UPDATE also locks skipped rows; identify the third row + // first so the barrier cannot block the first batch. + let third: Uuid = sqlx::query_scalar("SELECT id FROM api_tokens WHERE community_id=$1 AND owner_pubkey=decode($2,'hex') ORDER BY id OFFSET 2 LIMIT 1") + .bind(f.options.community).bind(TARGET).fetch_one(&f.pool).await.unwrap(); + sqlx::query("SELECT id FROM api_tokens WHERE community_id=$1 AND id=$2 FOR UPDATE") + .bind(f.options.community) + .bind(third) + .fetch_one(&mut *blocker) + .await + .unwrap(); + let (committed_tx, committed_rx) = tokio::sync::oneshot::channel(); + let store = f.store(); + let community = f.options.community; + let task = tokio::spawn(async move { + let mut sent = Some(committed_tx); + let mut writer = RecordWriter::new(move |r: &Value| { + if r["record"] == "batch_committed" { + if let Some(tx) = sent.take() { + let _ = tx.send(()); + } + } + Ok(()) + }); + let options = AccountBatchOptions { + community, + pubkey: TARGET.into(), + batch_size: 2, + max_items: 1000, + }; + store + .run_account_batches(&options, ExecutionMode::Delete, &mut writer, None) + .await + }); + let reached = tokio::time::timeout(Duration::from_secs(10), committed_rx).await; + task.abort(); + let stopped = task.await; + blocker.rollback().await.unwrap(); + reached.unwrap().unwrap(); + assert!(stopped.unwrap_err().is_cancelled()); + let after = f.snapshot().await; + assert_eq!( + after["api_tokens"].as_array().unwrap().len(), + before["api_tokens"].as_array().unwrap().len() - 2 + ); + assert_eq!( + f.run(ExecutionMode::Delete, &mut Vec::new()) + .await + .unwrap() + .items, + 33 + ); + f.assert_cleaned(&before, &[f.options.community]).await; +} diff --git a/crates/buzz-db/src/store/user_deletion/account_batches/postgres_tests/stage.rs b/crates/buzz-db/src/store/user_deletion/account_batches/postgres_tests/stage.rs new file mode 100644 index 0000000000..f9580199f7 --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/account_batches/postgres_tests/stage.rs @@ -0,0 +1,205 @@ +use super::*; +use crate::entity_deletion::{EntityLease, NewEntityStage, NextStage, StageTransition}; +use std::time::Duration; + +async fn prepare(f: &Fixture) -> (EntityLease, Uuid) { + let db = Db::from_pool(f.pool.clone()); + let request = f.store().submit(TARGET, "submitter", None).await.unwrap(); + f.store() + .approve( + request.id, + "approver", + request.inventory_digest.as_deref().unwrap(), + ) + .await + .unwrap(); + let store = db.entity_deletion_store(); + let lease = store + .claim(request.id, "worker", Duration::from_secs(60)) + .await + .unwrap() + .unwrap(); + let inputs = crate::user_deletion::UserDeletionInventory::read(&request) + .unwrap() + .inputs(TARGET, Some(f.options.community)) + .unwrap(); + // Gate/content are outside this handler's scope; initialize an approved + // account stage through the real transition/start APIs to exercise its guard. + let next = store + .transition_stage(&lease, None, |_, _| { + Ok(StageTransition::Initialize(NewEntityStage { + stage: "purge_account".into(), + community: Some(f.options.community), + inputs, + })) + }) + .await + .unwrap(); + let NextStage::Stage(row) = next else { + panic!("expected stage") + }; + store.start_stage(&lease, row.id).await.unwrap(); + (lease, row.id) +} + +async fn refused(f: &Fixture, lease: &EntityLease, id: Uuid) { + let before = f.snapshot().await; + assert!(f + .store() + .run_account_batches( + &f.options, + ExecutionMode::Delete, + &mut Vec::new(), + Some((lease, id)) + ) + .await + .is_err()); + assert_eq!(f.snapshot().await, before); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn approved_account_stage_runs_same_operations_without_advancing_workflow() { + let f = Fixture::new().await; + let (lease, id) = prepare(&f).await; + let before = f.snapshot().await; + let summary = f + .store() + .run_account_batches( + &f.options, + ExecutionMode::Delete, + &mut Vec::new(), + Some((&lease, id)), + ) + .await + .unwrap(); + assert_eq!(summary.items, 35); + assert!(summary.supported_scope_exhausted && !summary.account_erasure_complete); + f.assert_cleaned(&before, &[f.options.community]).await; +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn stale_expired_wrong_scope_or_unapproved_stages_cannot_mutate() { + let mut f = Fixture::new().await; + let (lease, id) = prepare(&f).await; + let stale = EntityLease { + generation: lease.generation - 1, + ..lease.clone() + }; + refused(&f, &stale, id).await; + refused(&f, &lease, Uuid::new_v4()).await; + let community = f.options.community; + f.options.community = f.other; + refused(&f, &lease, id).await; + f.options.community = community; + f.options.pubkey = "c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5".into(); + refused(&f, &lease, id).await; + f.options.pubkey = TARGET.into(); + for assignment in [ + "status='pending'", + "is_current=false", + "stage='purge_content'", + "metadata_json='{}'::jsonb", + ] { + let original: Value = sqlx::query_scalar( + "SELECT to_jsonb(r) FROM entity_deletion_stage_history r WHERE id=$1", + ) + .bind(id) + .fetch_one(&f.pool) + .await + .unwrap(); + sqlx::query(sqlx::AssertSqlSafe(format!( + "UPDATE entity_deletion_stage_history SET {assignment} WHERE id=$1" + ))) + .bind(id) + .execute(&f.pool) + .await + .unwrap(); + refused(&f, &lease, id).await; + sqlx::query("UPDATE entity_deletion_stage_history SET status=$2,is_current=$3,stage=$4,metadata_json=$5 WHERE id=$1") + .bind(id).bind(original["status"].as_str().unwrap()).bind(original["is_current"].as_bool().unwrap()) + .bind(original["stage"].as_str().unwrap()).bind(&original["metadata_json"]).execute(&f.pool).await.unwrap(); + } + sqlx::query("UPDATE entity_deletion_requests SET lease_expires_at=clock_timestamp()-interval '1 second' WHERE id=$1") + .bind(lease.request_id).execute(&f.pool).await.unwrap(); + refused(&f, &lease, id).await; + let renewed = Db::from_pool(f.pool.clone()) + .entity_deletion_store() + .claim(lease.request_id, "replacement", Duration::from_secs(60)) + .await + .unwrap() + .unwrap(); + refused(&f, &lease, id).await; + sqlx::query("DELETE FROM entity_deletion_approvals WHERE request_id=$1") + .bind(lease.request_id) + .execute(&f.pool) + .await + .unwrap(); + refused(&f, &renewed, id).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires Postgres"] +async fn lease_expiring_after_selection_rolls_back_current_batch() { + let f = Fixture::new().await; + let (lease, id) = prepare(&f).await; + sqlx::query("UPDATE entity_deletion_requests SET lease_expires_at=clock_timestamp()+interval '2 seconds' WHERE id=$1") + .bind(lease.request_id).execute(&f.pool).await.unwrap(); + let before = f.snapshot().await; + let (selected_tx, selected_rx) = tokio::sync::oneshot::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel(); + let store = f.store(); + let community = f.options.community; + let request_id = lease.request_id; + let task = tokio::spawn(async move { + let mut selected = Some(selected_tx); + let mut writer = failures_postgres_tests::RecordWriter::new(move |r: &Value| { + if r["record"] == "proposed_batch" { + if let Some(tx) = selected.take() { + let _ = tx.send(()); + // Write is synchronous; let Tokio keep driving database + // I/O and the expiry observer while this barrier waits. + tokio::task::block_in_place(|| { + release_rx.recv_timeout(Duration::from_secs(10)) + }) + .map_err(std::io::Error::other)?; + } + } + Ok(()) + }); + let options = AccountBatchOptions { + community, + pubkey: TARGET.into(), + batch_size: 2, + max_items: 1000, + }; + store + .run_account_batches( + &options, + ExecutionMode::Delete, + &mut writer, + Some((&lease, id)), + ) + .await + }); + let selected = tokio::time::timeout(Duration::from_secs(5), selected_rx).await; + // Observe the actual DB-clock deadline, rather than assuming a sleep won a race. + let expired = tokio::time::timeout(Duration::from_secs(5), async { + loop { + let expired: bool = sqlx::query_scalar("SELECT lease_expires_at <= clock_timestamp() FROM entity_deletion_requests WHERE id=$1") + .bind(request_id).fetch_one(&f.pool).await.unwrap(); + if expired { break; } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }).await; + let _ = release_tx.send(()); + let result = tokio::time::timeout(Duration::from_secs(5), task) + .await + .unwrap() + .unwrap(); + selected.unwrap().unwrap(); + expired.unwrap(); + assert!(result.unwrap_err().to_string().contains("lease")); + assert_eq!(f.snapshot().await, before); +} 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 new file mode 100644 index 0000000000..bf4fc2fbb5 --- /dev/null +++ b/crates/buzz-db/src/store/user_deletion/account_batches/scope.rs @@ -0,0 +1,201 @@ +//! Community selection for the offline account command, independent of membership. +use super::*; +use serde::Deserialize; +use std::collections::BTreeSet; + +const MAX_TARGETS: usize = 10_000; + +/// Saved account cleanup inputs. Agent keys are a discovery snapshot only; +/// each handler fetches current ownership. Keep ownership rows until cleanup ends. +#[derive(Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AccountScope { + /// Current manifest version. + pub version: u32, + /// Human key, canonical lowercase hex. + pub target: String, + /// Every stored community, including ones with no current membership. + pub communities: Vec, + /// Explicit retention limits; these are not proof of full erasure. + pub retained: Vec, +} + +/// Frozen human and directly owned agent keys in one community. +#[derive(Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AccountCommunityScope { + /// Database community identity. + pub community: Uuid, + /// Human plus agents whose ownership was recorded in this community. + pub pubkeys: Vec, +} + +impl AccountScope { + /// Reject malformed, oversized or duplicate scope before any mutation. + pub fn validate(&self) -> Result<()> { + if self.version != 1 || normalize_user_deletion_pubkey(&self.target)? != self.target { + return Err(invalid( + "unsupported account scope version or noncanonical target", + )); + } + if self.communities.len() > super::super::MAX_COMMUNITIES { + return Err(invalid("account scope exceeds community limit")); + } + let mut communities = BTreeSet::new(); + let mut count = 0; + for row in &self.communities { + let mut keys = BTreeSet::new(); + if !communities.insert(row.community) || !row.pubkeys.contains(&self.target) { + return Err(invalid( + "duplicate community or missing human in account scope", + )); + } + for key in &row.pubkeys { + count += 1; + if count > MAX_TARGETS + || normalize_user_deletion_pubkey(key)? != *key + || !keys.insert(key) + { + return Err(invalid( + "invalid, duplicate or excessive account scope keys", + )); + } + } + } + Ok(()) + } +} + +impl UserDeletionStore { + /// Read-only account scope capture. Scan all communities rather than infer + /// residue from current memberships. Agent authority is community-scoped; + /// global agent records are retained where exclusive ownership is unproven. + pub async fn generate_account_scope(&self, pubkey: &str) -> Result { + let target = normalize_user_deletion_pubkey(pubkey)?; + let mut tx = self.pool.begin().await?; + sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY") + .execute(&mut *tx) + .await?; + sqlx::query("SET LOCAL statement_timeout='30s'") + .execute(&mut *tx) + .await?; + let communities: Vec = + sqlx::query_scalar("SELECT id FROM communities ORDER BY id LIMIT $1") + .bind((super::super::MAX_COMMUNITIES + 1) as i64) + .fetch_all(&mut *tx) + .await?; + 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 scope = AccountScope { + version: 1, + target: target.clone(), + communities: communities.into_iter().map(|community| { + let mut pubkeys = vec![target.clone()]; + pubkeys.extend(agents.iter().filter(|(id,_)| *id == community).map(|(_,key)| key.clone())); + AccountCommunityScope { community, pubkeys } + }).collect(), + retained: vec!["global agent records: ownership is community-scoped; no exclusive deployment-wide attribution".into(), + "shared ownership, moderation/audit, device registrations and historical signed membership snapshots: see operator-user-account-retention.md".into()], + }; + scope.validate()?; + tx.commit().await?; + Ok(scope) + } + + /// Execute the selected communities with one invocation-wide row budget. + /// Saved agent keys never authorize deletion; each handler fetches them again. + /// This direct offline command does not bypass or rewrite workflow approval. + pub async fn run_account_scope( + &self, + scope: &AccountScope, + actor: &str, + batch_size: u16, + max_items: u32, + mode: ExecutionMode, + writer: &mut impl Write, + ) -> Result { + scope.validate()?; + bounds(batch_size, max_items)?; + let actor = normalize_user_deletion_pubkey(actor)?; + // Whole-community ownership must go through its existing handoff. Check + // every scope before global work so a later owner cannot cause partial + // cleanup of a plan that cannot be executed safely. + for row in &scope.communities { + let mut tx = self.pool.begin().await?; + timeouts(&mut tx).await?; + let mut keys = vec![scope.target.clone()]; + keys.extend(ownership::agents(&mut tx, row.community, &scope.target, false).await?); + tx.rollback().await?; + if mode == ExecutionMode::Delete { + self.preflight_memberships(row.community, &keys).await?; + } + let owned: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM relay_members WHERE community_id=$1 AND pubkey=ANY($2) AND role='owner')") + .bind(row.community).bind(&keys).fetch_one(&self.pool).await?; + if owned { + return Err(invalid( + "owned-community handoff required; account scope was not executed", + )); + } + } + let mut total = AccountBatchSummary { + record: "account_scope_summary", + read_only: mode == ExecutionMode::ReadOnly, + items: 0, + batches: 0, + supported_scope_exhausted: true, + account_erasure_complete: false, + }; + line( + writer, + &json!({"record":"account_scope_start","target":scope.target,"communities":scope.communities.len(),"retained":scope.retained,"read_only":total.read_only}), + )?; + // Global work runs even with no communities. Never hide it in a first + // community stage or choose a fabricated community UUID. + let summary = self + .run_global_account_batches( + &GlobalAccountBatchOptions { + pubkey: scope.target.clone(), + actor, + batch_size, + max_items, + }, + mode, + writer, + ) + .await?; + total.items += summary.items; + total.batches += summary.batches; + total.supported_scope_exhausted = summary.supported_scope_exhausted; + for row in &scope.communities { + if !total.supported_scope_exhausted || total.items == max_items { + total.supported_scope_exhausted = false; + break; + } + let summary = self + .run_account_batches( + &AccountBatchOptions { + community: row.community, + pubkey: scope.target.clone(), + batch_size, + max_items: max_items - total.items, + }, + mode, + writer, + None, + ) + .await?; + total.items += summary.items; + total.batches += summary.batches; + total.supported_scope_exhausted = summary.supported_scope_exhausted; + } + line(writer, &total)?; + Ok(total) + } +} diff --git a/crates/buzz-db/src/store/user_deletion/mod.rs b/crates/buzz-db/src/store/user_deletion/mod.rs index ea92eecedd..261f12cb7f 100644 --- a/crates/buzz-db/src/store/user_deletion/mod.rs +++ b/crates/buzz-db/src/store/user_deletion/mod.rs @@ -1,6 +1,8 @@ //! User-specific submission and inventory preparation over the shared deletion tables. use crate::Db; use sqlx::PgPool; +/// Bounded cleanup of one human's community account records. +pub mod account_batches; /// Ordered user and owned-agent content cleanup in read-only and delete modes. pub mod content_batches; mod discovery; @@ -10,18 +12,29 @@ mod requests; pub use discovery::normalize_user_deletion_pubkey; pub use inventory::UserDeletionInventory; +/// Select whether a cleanup handler reports or applies its operations. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ExecutionMode { + /// Report operations without changing source data. + ReadOnly, + /// Apply the reported operations. + Delete, +} + const MAX_COMMUNITIES: usize = 1000; /// Database operations that prepare user-deletion requests. #[derive(Clone)] pub struct UserDeletionStore { pool: PgPool, + account_snapshot_signer: Option, } impl Db { /// Access user-specific deletion request preparation using the writer pool. pub fn user_deletion_store(&self) -> UserDeletionStore { UserDeletionStore { pool: self.pool().clone(), + account_snapshot_signer: None, } } } @@ -33,11 +46,11 @@ mod postgres_tests; #[cfg(test)] mod discovery_postgres_tests; -/// Controls source-data effects for user-deletion handlers. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ExecutionMode { - /// Print the selected rows without changing source data. - ReadOnly, - /// Delete the selected rows. - Delete, +impl UserDeletionStore { + /// Configure the deployment's existing relay key for atomic account roster repair. + /// Never generate an ephemeral key: readers trust the serving relay's identity. + pub fn with_account_snapshot_signer(mut self, signer: nostr::Keys) -> Self { + self.account_snapshot_signer = Some(signer); + self + } } diff --git a/crates/buzz-deletion/Cargo.toml b/crates/buzz-deletion/Cargo.toml index d4bf1fe748..4be18aec49 100644 --- a/crates/buzz-deletion/Cargo.toml +++ b/crates/buzz-deletion/Cargo.toml @@ -17,6 +17,7 @@ buzz-pubsub = { workspace = true } chrono = { workspace = true } clap = { version = "4", features = ["derive"] } hex = { workspace = true } +nostr = { workspace = true } redis = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } @@ -27,4 +28,3 @@ uuid = { workspace = true } [dev-dependencies] url = { workspace = true } -nostr = { workspace = true } diff --git a/crates/buzz-deletion/src/user.rs b/crates/buzz-deletion/src/user.rs index c549d52176..74ff6193b7 100644 --- a/crates/buzz-deletion/src/user.rs +++ b/crates/buzz-deletion/src/user.rs @@ -1,16 +1,25 @@ -//! User inventory, content cleanup and resumable deletion workflows. +//! User inventory, offline account cleanup and persisted deletion workflows. -use anyhow::Result; +use anyhow::{bail, Result}; +use buzz_db::user_deletion::ExecutionMode; use clap::Subcommand; use uuid::Uuid; -/// Inspect user data, run content cleanup, or advance a deletion request. +/// Inspect user data, run account cleanup or execute persisted workflows. #[derive(Debug, Subcommand)] pub enum Command { /// Inspect or delete one human's community content. ContentBatches(content_batches::Args), - /// Run the media handler directly, without a workflow request. + /// Run media cleanup directly, without a workflow request. MediaBatches(media::Args), + /// Print account-table batches for one community; --delete executes offline. + AccountBatches(account_batches::Args), + /// Capture frozen human/agent inputs across stored communities, read-only. + AccountScope { + /// Human public key, hex or npub. + #[arg(long, value_parser = inventory::parse_subject)] + pubkey: String, + }, /// Print real current memberships as JSON; does not save or execute a request. Inventory { /// Demo fixture (default), hex public key, or npub. Current memberships only. @@ -43,21 +52,21 @@ pub enum Command { #[arg(long)] inventory_digest: String, }, - /// Run approved workflow stages; real cleanup requires --delete. + /// Run an approved workflow; real handlers require explicit --delete. Run { /// Approved request UUID. id: Uuid, - /// Execute implemented handlers for a real request. + /// Execute implemented real handlers; stop relay and external writers first. #[arg(long)] delete: bool, /// Trusted relay signer for historical content attribution. #[arg(long, value_parser=content_batches::parse_pubkey)] relay_pubkey: Option, - /// Maximum explicit row operations per content batch. + /// Maximum explicit row operations per batch. #[arg(long, default_value_t=100, value_parser=clap::value_parser!(u16).range(1..=100))] batch_size: u16, - /// Maximum content operations per invocation. - #[arg(long, default_value_t=1_000_000, value_parser=clap::value_parser!(u32).range(1..=1_000_000))] + /// Maximum row operations in one handler invocation. + #[arg(long, default_value_t=100_000, value_parser=clap::value_parser!(u32).range(1..=1_000_000))] max_items: u32, /// Worker identity; defaults to hostname and process id. #[arg(long)] @@ -88,14 +97,43 @@ pub enum Command { }, } -/// Run the selected inventory, cleanup or workflow command against PostgreSQL. +/// Run the selected user-deletion command against PostgreSQL. pub async fn run(command: Command) -> Result { let command = match command { Command::ContentBatches(args) => return content_batches::run_command(args).await, Command::MediaBatches(args) => return media::run(args).await, - other => other, + command => command, }; - let db = if matches!(command, Command::Inventory { .. }) { + if let Command::AccountBatches(args) = command { + let mode = if args.delete { + ExecutionMode::Delete + } else { + ExecutionMode::ReadOnly + }; + // Command setup stays outside the handler. Neither mode runs startup + // migrations or connects to Redis; preview defaults to read-only SQL. + 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: mode == ExecutionMode::ReadOnly, + ..buzz_db::DbConfig::default() + }, + "user_account_batches", + ) + .await?; + let summary = account_batches::run_command(&db, args, mode).await?; + return Ok(if summary.supported_scope_exhausted { + 0 + } else { + 2 + }); + } + let db = if matches!( + command, + Command::Inventory { .. } | Command::AccountScope { .. } + ) { buzz_db::Db::connect_cold_start( buzz_db::DbConfig { database_url: crate::required_env("DATABASE_URL")?, @@ -113,7 +151,15 @@ pub async fn run(command: Command) -> Result { let store = db.entity_deletion_store(); match command { Command::ContentBatches(_) | Command::MediaBatches(_) => { - anyhow::bail!("direct command was already dispatched") + bail!("direct cleanup command dispatched above") + } + Command::AccountBatches(_) => anyhow::bail!("account command dispatched above"), + Command::AccountScope { pubkey } => { + crate::print_json( + &db.user_deletion_store() + .generate_account_scope(&pubkey) + .await?, + )?; } Command::Inventory { pubkey } => { crate::print_json(&inventory::generate(&db, &pubkey).await?)?; @@ -146,23 +192,23 @@ pub async fn run(command: Command) -> Result { } Command::Run { id, + delete, + relay_pubkey, + batch_size, + max_items, executor_id, next_step, fail_stage, stage_delay_ms, demo_no_agents_in, - delete, - relay_pubkey, - batch_size, - max_items, } => { let request = store.get(id).await?; - let is_real = !request.target.starts_with("demo:"); - if is_real { - anyhow::ensure!(delete, "real workflow execution requires --delete; inspect with content-batches --read-only"); + let real = !request.target.starts_with("demo:"); + if real { + anyhow::ensure!(delete, "real workflow execution requires --delete; use account-batches --read-only to preview"); anyhow::ensure!( fail_stage.is_none() && stage_delay_ms == 0 && demo_no_agents_in.is_empty(), - "dummy controls cannot be used for real requests" + "dummy controls cannot be used for real deletion" ); } let code = worker::run( @@ -170,13 +216,13 @@ pub async fn run(command: Command) -> Result { id, &executor_id.unwrap_or_else(crate::default_executor_id), &worker::RunOptions { - next_step, + db: real.then(|| buzz_db::Db::from_pool(db.pool().clone())), media: None, - db: is_real.then(|| buzz_db::Db::from_pool(db.pool().clone())), delete, relay_pubkey, batch_size, max_items, + next_step, fail_stage, stage_delay: std::time::Duration::from_millis(stage_delay_ms), no_agents_in: demo_no_agents_in, @@ -193,6 +239,7 @@ pub async fn run(command: Command) -> Result { Ok(0) } +mod account_batches; mod content_batches; mod handlers; mod inventory; diff --git a/crates/buzz-deletion/src/user/account_batches.rs b/crates/buzz-deletion/src/user/account_batches.rs new file mode 100644 index 0000000000..fab7fdce35 --- /dev/null +++ b/crates/buzz-deletion/src/user/account_batches.rs @@ -0,0 +1,265 @@ +//! One account cleanup handler; the mode chooses printing or deletion. +use anyhow::Result; +use buzz_db::entity_deletion::EntityLease; +use buzz_db::user_deletion::{ + account_batches::{ + AccountBatchOptions, AccountBatchSummary, AccountScope, GlobalAccountBatchOptions, + }, + ExecutionMode, +}; +use uuid::Uuid; + +/// Arguments for the account-table debugging command. +#[derive(Debug, clap::Args)] +pub struct Args { + /// Human public key, in hex or npub form. + #[arg(long, value_parser = parse_pubkey, required_unless_present = "scope_file", conflicts_with = "scope_file")] + pub(super) pubkey: Option, + /// One surviving community selected by the caller. + #[arg(long, required_unless_present_any = ["global", "scope_file"], conflicts_with_all = ["global", "scope_file"])] + pub(super) community: Option, + /// Explicitly clean deployment-wide listeners, feedback and DB roles. + #[arg(long, group = "wide_scope", requires = "actor", conflicts_with_all = ["community", "scope_file"])] + pub(super) global: bool, + /// Audit identity performing global role revocation (hex or npub). + #[arg(long, value_parser = parse_pubkey, requires = "wide_scope")] + pub(super) actor: Option, + /// Output of account-scope selecting communities; agents are fetched on every run. + #[arg(long, group = "wide_scope", requires = "actor", conflicts_with_all = ["community", "global", "pubkey"])] + pub(super) scope_file: Option, + /// Print proposals only (default); does not change data, progress, or caches. + #[arg(long, alias = "read-only", conflicts_with = "delete")] + print_only: bool, + /// Execute printed batches. Stop the relay and external workers first. + #[arg(long, conflicts_with = "print_only")] + pub(super) delete: bool, + /// Maximum explicit row operations per transaction. + #[arg(long, default_value_t = 100, value_parser = clap::value_parser!(u16).range(1..=100))] + pub(super) batch_size: u16, + /// Stop after this many row operations; rerun delete to continue. + #[arg(long, default_value_t = 100_000, value_parser = clap::value_parser!(u32).range(1..=1_000_000))] + pub(super) max_items: u32, +} + +fn parse_pubkey(value: &str) -> std::result::Result { + buzz_db::user_deletion::normalize_user_deletion_pubkey(value).map_err(|error| error.to_string()) +} + +pub(super) async fn run( + db: &buzz_db::Db, + options: &AccountBatchOptions, + mode: ExecutionMode, + stage: Option<(&EntityLease, Uuid)>, +) -> Result { + let store = store(db, mode)?; + // Workflow stdout is a single inspection document; direct commands emit NDJSON. + if stage.is_some() { + Ok(store + .run_account_batches(options, mode, &mut std::io::stderr(), stage) + .await?) + } else { + Ok(store + .run_account_batches(options, mode, &mut std::io::stdout(), stage) + .await?) + } +} + +/// Run the explicitly selected scope; global work is never inferred from a +/// community or from the absence of community memberships. +pub(super) async fn run_command( + db: &buzz_db::Db, + args: Args, + mode: ExecutionMode, +) -> Result { + if let Some(path) = &args.scope_file { + // Bound input before parsing; a bad file must fail before any database mutation. + use std::io::Read; + let mut bytes = Vec::new(); + std::fs::File::open(path)? + .take(4 * 1024 * 1024 + 1) + .read_to_end(&mut bytes)?; + anyhow::ensure!( + bytes.len() <= 4 * 1024 * 1024, + "account scope exceeds 4 MiB" + ); + let scope: AccountScope = serde_json::from_slice(&bytes)?; + scope.validate()?; + if mode == ExecutionMode::Delete && configured_operator(&scope.target)? { + anyhow::bail!("target is a config-backed operator; remove that authority from every relay configuration before offline cleanup"); + } + return Ok(store(db, mode)? + .run_account_scope( + &scope, + args.actor + .as_deref() + .ok_or_else(|| anyhow::anyhow!("scope cleanup requires --actor"))?, + args.batch_size, + args.max_items, + mode, + &mut std::io::stdout(), + ) + .await?); + } + let pubkey = args + .pubkey + .ok_or_else(|| anyhow::anyhow!("missing --pubkey"))?; + if args.global { + if mode == ExecutionMode::Delete && configured_operator(&pubkey)? { + anyhow::bail!("target is a config-backed operator; remove that authority from every relay configuration before offline cleanup"); + } + Ok(store(db, mode)? + .run_global_account_batches( + &GlobalAccountBatchOptions { + pubkey, + actor: args + .actor + .ok_or_else(|| anyhow::anyhow!("global cleanup requires --actor"))?, + batch_size: args.batch_size, + max_items: args.max_items, + }, + mode, + &mut std::io::stdout(), + ) + .await?) + } else { + run( + db, + &AccountBatchOptions { + community: args + .community + .ok_or_else(|| anyhow::anyhow!("missing --community"))?, + pubkey, + batch_size: args.batch_size, + max_items: args.max_items, + }, + mode, + None, + ) + .await + } +} + +// Preview never needs secret material and never invokes the signing path. +fn store( + db: &buzz_db::Db, + mode: ExecutionMode, +) -> Result { + let store = db.user_deletion_store(); + if mode == ExecutionMode::ReadOnly { + return Ok(store); + } + match std::env::var("BUZZ_RELAY_PRIVATE_KEY") { + Ok(value) => Ok(store.with_account_snapshot_signer( + nostr::Keys::parse(&value) + .map_err(|_| anyhow::anyhow!("invalid BUZZ_RELAY_PRIVATE_KEY"))?, + )), + Err(std::env::VarError::NotPresent) => Ok(store), + Err(_) => anyhow::bail!("invalid BUZZ_RELAY_PRIVATE_KEY"), + } +} + +// This catches local configuration; an offline CLI cannot attest every relay's +// deployed config. Do not treat absence here as proof of authority revocation. +fn configured_operator(target: &str) -> Result { + let list = std::env::var("RELAY_OPERATOR_PUBKEYS").unwrap_or_default(); + let owner = std::env::var("RELAY_OWNER_PUBKEY").unwrap_or_default(); + configured_operator_in(target, &list, &owner) +} + +fn configured_operator_in(target: &str, list: &str, owner: &str) -> Result { + let mut keys = Vec::new(); + for value in list.split(',').map(str::trim).filter(|s| !s.is_empty()) { + keys.push(parse_pubkey(value).map_err(anyhow::Error::msg)?); + } + if keys.is_empty() && !owner.trim().is_empty() { + keys.push(parse_pubkey(owner.trim()).map_err(anyhow::Error::msg)?); + } + Ok(keys.iter().any(|key| key == target)) +} + +#[cfg(test)] +mod tests { + use super::*; + use clap::Parser; + + #[derive(Parser)] + struct Cli { + #[command(flatten)] + args: Args, + } + + #[test] + fn global_scope_requires_explicit_actor_and_config_uses_owner_fallback() { + let target = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; + assert!(Cli::try_parse_from(["account-batches", "--pubkey", target, "--global"]).is_err()); + assert!(Cli::try_parse_from([ + "account-batches", + "--pubkey", + target, + "--global", + "--actor", + target + ]) + .is_ok()); + assert!(Cli::try_parse_from([ + "account-batches", + "--scope-file", + "scope.json", + "--actor", + target + ]) + .is_ok()); + assert!(Cli::try_parse_from([ + "account-batches", + "--scope-file", + "scope.json", + "--pubkey", + target, + "--actor", + target + ]) + .is_err()); + assert!(configured_operator_in(target, "", target).unwrap()); + assert!(configured_operator_in(target, &target.to_uppercase(), "").unwrap()); + assert!(!configured_operator_in( + target, + "2222222222222222222222222222222222222222222222222222222222222222", + target + ) + .unwrap()); + assert!(configured_operator_in(target, "bad", "").is_err()); + } + + #[test] + fn modes_default_to_print_and_conflicts_are_errors() { + let base = [ + "account-batches", + "--pubkey", + "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "--community", + "00000000-0000-0000-0000-000000000001", + ]; + for mode in [None, Some("--print-only"), Some("--read-only")] { + let mut args = base.to_vec(); + args.extend(mode); + assert!(!Cli::try_parse_from(args).unwrap().args.delete); + } + assert!( + Cli::try_parse_from(base.into_iter().chain(["--delete"])) + .unwrap() + .args + .delete + ); + for preview in ["--print-only", "--read-only"] { + assert!(Cli::try_parse_from(base.into_iter().chain([preview, "--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()); + } + } +} diff --git a/crates/buzz-deletion/src/user/account_worker_postgres_tests.rs b/crates/buzz-deletion/src/user/account_worker_postgres_tests.rs new file mode 100644 index 0000000000..8082c20bc3 --- /dev/null +++ b/crates/buzz-deletion/src/user/account_worker_postgres_tests.rs @@ -0,0 +1,363 @@ +//! Start at an approved account stage; the preceding handlers are +//! fixture preconditions, while account dispatch, persistence and release are real. + +use super::*; +use buzz_db::{entity_deletion::EntityInspection, Db}; +use serde_json::json; +use sqlx::PgPool; + +const TARGET: &str = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"; + +struct Fixture { + pool: PgPool, + store: EntityDeletionStore, + request: Uuid, + community: Uuid, + stage: Uuid, +} + +impl Fixture { + async fn new() -> Self { + let url = std::env::var("BUZZ_TEST_DATABASE_URL") + .or_else(|_| std::env::var("DATABASE_URL")) + .unwrap(); + let pool = PgPool::connect(&url).await.unwrap(); + let db = Db::from_pool(pool.clone()); + if std::env::var("BUZZ_TEST_SCHEMA_MODE").as_deref() != Ok("desired") { + db.migrate().await.unwrap(); + } + let community = Uuid::new_v4(); + sqlx::query("INSERT INTO communities(id,host) VALUES ($1,$2)") + .bind(community) + .bind(format!("{community}.example.org")) + .execute(&pool) + .await + .unwrap(); + sqlx::query("INSERT INTO users(community_id,pubkey) VALUES ($1,decode($2,'hex'))") + .bind(community) + .bind(TARGET) + .execute(&pool) + .await + .unwrap(); + sqlx::query("INSERT INTO relay_members(community_id,pubkey,role) VALUES ($1,$2,'member')") + .bind(community) + .bind(TARGET) + .execute(&pool) + .await + .unwrap(); + for n in 1..=3 { + sqlx::query("INSERT INTO api_tokens(community_id,id,owner_pubkey,token_hash,name,scopes) VALUES ($1,$2,decode($3,'hex'),$4,'fixture','[]')") + .bind(community).bind(Uuid::from_u128(n)).bind(TARGET) + .bind(vec![n as u8; 32]).execute(&pool).await.unwrap(); + } + let request = db + .user_deletion_store() + .submit(TARGET, "submitter", None) + .await + .unwrap(); + let store = db.entity_deletion_store(); + store + .approve( + request.id, + "approver", + request.inventory_digest.as_deref().unwrap(), + ) + .await + .unwrap(); + let lease = store + .claim(request.id, "fixture", DEFAULT_LEASE_DURATION) + .await + .unwrap() + .unwrap(); + let transition = UserDeletionTransition::new(&store); + // Save explicit prerequisites through the storage APIs. Do not run or + // pretend to exercise the preceding handlers in this account retry test. + for name in ["gate_user", "purge_media", "purge_content"] { + let NextStage::Stage(row) = transition.get_next_stage(&lease, None).await.unwrap() + else { + panic!("expected prerequisite stage"); + }; + assert_eq!(row.stage, name); + store.start_stage(&lease, row.id).await.unwrap(); + store + .save_stage_success( + &lease, + row.id, + if name == "purge_content" { + json!({"content": {}, "account_erasure_complete": false}) + } else { + json!({"fixture_prerequisite": true}) + }, + ) + .await + .unwrap(); + } + let NextStage::Stage(row) = transition.get_next_stage(&lease, None).await.unwrap() else { + panic!("expected account stage"); + }; + assert_eq!(row.stage, "purge_account"); + assert_eq!(row.status, "pending"); + assert_eq!(row.target_community_id, Some(community)); + store.release(&lease).await.unwrap(); + // This worker journey covers a former member's credentials. The real + // CLI journey supplies a process-local signing key for roster cleanup. + sqlx::query("DELETE FROM relay_members WHERE community_id=$1 AND pubkey=$2") + .bind(community) + .bind(TARGET) + .execute(&pool) + .await + .unwrap(); + Self { + pool, + store, + request: request.id, + community, + stage: row.id, + } + } + + fn options(&self, max_items: u32) -> RunOptions { + RunOptions { + db: Some(Db::from_pool(self.pool.clone())), + media: None, + delete: true, + relay_pubkey: None, + batch_size: 2, + max_items, + next_step: true, + fail_stage: None, + stage_delay: Duration::ZERO, + no_agents_in: Vec::new(), + } + } + + async fn tokens(&self) -> Vec { + sqlx::query_scalar("SELECT id FROM api_tokens WHERE community_id=$1 ORDER BY id") + .bind(self.community) + .fetch_all(&self.pool) + .await + .unwrap() + } + + async fn inspect_released(&self) -> EntityInspection { + let state = self.store.inspect(self.request).await.unwrap(); + assert!(state.execution.lease_owner.is_none()); + assert!(state.execution.lease_expires_at.is_none()); + assert!(state.execution.completed_at.is_none()); + state + } + + async fn waiting_on(&self, blocker_pid: i32) -> bool { + sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE datname=current_database() AND $1=ANY(pg_blocking_pids(pid)))") + .bind(blocker_pid).fetch_one(&self.pool).await.unwrap() + } + + async fn assert_account_saved(&self, items: u32) { + assert!(self.tokens().await.is_empty()); + let memberships: i64 = sqlx::query_scalar( + "SELECT count(*) FROM relay_members WHERE community_id=$1 AND pubkey=$2", + ) + .bind(self.community) + .bind(TARGET) + .fetch_one(&self.pool) + .await + .unwrap(); + assert_eq!(memberships, 0); + let state = self.inspect_released().await; + // A successful account stage does not imply complete user erasure. + assert_eq!(state.request.status, "running"); + assert_eq!(state.execution.retry_count, 0); + assert!(state.execution.last_error.is_none()); + assert!(state.execution.next_attempt_at.is_none()); + assert_eq!(state.stage_history.len(), 5); + let account = state + .stage_history + .iter() + .find(|s| s.id == self.stage) + .unwrap(); + assert_eq!(account.status, "completed"); + assert!(!account.is_current); + assert!(account.finished_at.is_some()); + assert!(account.last_error.is_none()); + assert_eq!(account.metadata_json["result"]["items"], items); + assert_eq!( + account.metadata_json["result"]["supported_scope_exhausted"], + true + ); + assert_eq!( + account.metadata_json["result"]["account_erasure_complete"], + false + ); + assert_eq!( + account.metadata_json["transition"], + json!({"kind":"stage","stage":"purge_agents"}) + ); + let next = state.stage_history.iter().find(|s| s.is_current).unwrap(); + assert_eq!(next.stage, "purge_agents"); + assert_eq!(next.status, "pending"); + assert!(next.started_at.is_none()); + } +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn real_account_cap_saves_failure_then_retry_saves_success() { + let f = Fixture::new().await; + let error = tokio::time::timeout( + Duration::from_secs(10), + run( + &f.store, + f.request, + "capped-worker", + &f.options(1), + &CancellationToken::new(), + ), + ) + .await + .unwrap() + .unwrap_err(); + assert!(error.to_string().contains("account batch limit reached")); + assert_eq!( + f.tokens().await, + vec![Uuid::from_u128(2), Uuid::from_u128(3)] + ); + let failed = f.inspect_released().await; + assert_eq!(failed.request.status, "retry_wait"); + assert_eq!(failed.execution.retry_count, 1); + assert!(failed.execution.next_attempt_at.is_some()); + assert!(failed + .execution + .last_error + .as_deref() + .unwrap() + .contains("account batch limit reached")); + let account = failed + .stage_history + .iter() + .find(|s| s.id == f.stage) + .unwrap(); + assert_eq!(account.status, "failed"); + assert!(account.is_current); + assert!(account.metadata_json.get("result").is_none()); + assert!(account + .last_error + .as_deref() + .unwrap() + .contains("account batch limit reached")); + // Ownership changed after approval and the first invocation. The real + // workflow retry must discover this direct agent while retaining its source. + let agent = "22".repeat(32); + sqlx::query("INSERT INTO users(community_id,pubkey,agent_owner_pubkey) VALUES ($1,decode($2,'hex'),decode($3,'hex'))") + .bind(f.community).bind(&agent).bind(TARGET).execute(&f.pool).await.unwrap(); + sqlx::query("INSERT INTO api_tokens(community_id,id,owner_pubkey,token_hash,name,scopes) VALUES ($1,$2,decode($3,'hex'),$4,'agent retry','[]')") + .bind(f.community).bind(Uuid::new_v4()).bind(&agent).bind(vec![9u8;32]).execute(&f.pool).await.unwrap(); + let started = account.started_at; + // Retry timing is a storage precondition, not a sleep in this regression. + sqlx::query("UPDATE entity_deletion_requests SET next_attempt_at=clock_timestamp()-interval '1 second' WHERE id=$1") + .bind(f.request).execute(&f.pool).await.unwrap(); + assert_eq!( + tokio::time::timeout( + Duration::from_secs(10), + run( + &f.store, + f.request, + "retry-worker", + &f.options(100), + &CancellationToken::new() + ), + ) + .await + .unwrap() + .unwrap(), + 0 + ); + f.assert_account_saved(3).await; + let resumed = f.inspect_released().await; + assert_eq!( + resumed.execution.lease_generation, + failed.execution.lease_generation + 1 + ); + assert_eq!( + resumed + .stage_history + .iter() + .find(|s| s.id == f.stage) + .unwrap() + .started_at, + started + ); +} + +#[tokio::test] +#[ignore = "requires Postgres"] +async fn real_account_cancellation_releases_lease_and_resumes_committed_batches() { + let f = Fixture::new().await; + let mut blocker = f.pool.begin().await.unwrap(); + let blocker_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&mut *blocker) + .await + .unwrap(); + // Batch one deletes tokens 1 and 2. Hold token 3 so further progress must + // wait; cancellation must finish even while this barrier stays locked. + sqlx::query("SELECT id FROM api_tokens WHERE community_id=$1 AND id=$2 FOR UPDATE") + .bind(f.community) + .bind(Uuid::from_u128(3)) + .fetch_one(&mut *blocker) + .await + .unwrap(); + let shutdown = CancellationToken::new(); + let options = f.options(100); + let work = run(&f.store, f.request, "cancelled-worker", &options, &shutdown); + tokio::pin!(work); + let committed = tokio::time::timeout(Duration::from_secs(5), async { + loop { + tokio::select! { + result = &mut work => panic!("worker finished before cancellation: {result:?}"), + _ = tokio::time::sleep(Duration::from_millis(10)) => { + if f.tokens().await == vec![Uuid::from_u128(3)] + && f.waiting_on(blocker_pid).await { break; } + } + } + } + }) + .await; + shutdown.cancel(); + let stopped = tokio::time::timeout(Duration::from_secs(5), &mut work).await; + // Always release the barrier before asserting, including timeout paths. + blocker.rollback().await.unwrap(); + committed.unwrap(); + assert_eq!(stopped.unwrap().unwrap(), 0); + assert_eq!(f.tokens().await, vec![Uuid::from_u128(3)]); + let paused = f.inspect_released().await; + assert_eq!(paused.request.status, "running"); + let account = paused + .stage_history + .iter() + .find(|s| s.id == f.stage) + .unwrap(); + assert_eq!(account.status, "running"); + assert!(account.is_current); + assert!(account.metadata_json.get("result").is_none()); + assert!(account.finished_at.is_none()); + assert_eq!( + tokio::time::timeout( + Duration::from_secs(10), + run( + &f.store, + f.request, + "replacement-worker", + &options, + &CancellationToken::new() + ), + ) + .await + .unwrap() + .unwrap(), + 0 + ); + f.assert_account_saved(1).await; + assert_eq!( + f.inspect_released().await.execution.lease_generation, + paused.execution.lease_generation + 1 + ); +} diff --git a/crates/buzz-deletion/src/user/handlers.rs b/crates/buzz-deletion/src/user/handlers.rs index 863434723d..2753fca850 100644 --- a/crates/buzz-deletion/src/user/handlers.rs +++ b/crates/buzz-deletion/src/user/handlers.rs @@ -1,11 +1,12 @@ -//! Workflow handlers validate saved scope and persist outcomes; they never route. +//! Dispatch real account cleanup or demo handlers; transitions own routing. use super::worker::RunOptions; use crate::RETRY_DELAY; use anyhow::{bail, ensure, Context, Result}; -use buzz_db::{ - entity_deletion::{EntityDeletionStore, EntityLease, EntityStage}, - user_deletion::{content_batches::ContentBatchOptions, ExecutionMode, UserDeletionInventory}, +use buzz_db::entity_deletion::{EntityDeletionStore, EntityLease, EntityStage}; +use buzz_db::user_deletion::{ + account_batches::AccountBatchOptions, content_batches::ContentBatchOptions, ExecutionMode, + UserDeletionInventory, }; use uuid::Uuid; @@ -17,13 +18,59 @@ pub(super) async fn dispatch( ) -> Result<()> { let target = row.metadata_json["inputs"]["target"] .as_str() - .unwrap_or_default(); + .ok_or_else(|| anyhow::anyhow!("missing target input"))?; + if !target.starts_with("demo:") && row.stage == "purge_media" { + return purge_media(store, lease, row, options).await; + } if !target.starts_with("demo:") { - return match row.stage.as_str() { - "purge_content" => purge_content(store, lease, row, options).await, - "purge_media" => purge_media(store, lease, row, options).await, - name => bail!("real handler {name} is not implemented"), - }; + if row.stage == "purge_content" { + return purge_content(store, lease, row, options).await; + } + if row.stage == "purge_account" { + ensure!(options.delete, "real workflow execution requires --delete"); + let db = options.db.as_ref().context("missing account database")?; + let row = store.start_stage(lease, row.id).await?; + let result = async { + let target = row.metadata_json["inputs"]["target"] + .as_str() + .context("missing target")?; + let community = row + .target_community_id + .context("missing account community")?; + let summary = super::account_batches::run( + db, + &AccountBatchOptions { + community, + pubkey: target.to_owned(), + batch_size: options.batch_size, + max_items: options.max_items, + }, + ExecutionMode::Delete, + Some((lease, row.id)), + ) + .await?; + ensure!( + summary.supported_scope_exhausted, + "account batch limit reached; rerun to continue" + ); + Ok::<_, anyhow::Error>(serde_json::to_value(summary)?) + } + .await; + match result { + Ok(value) => store.save_stage_success(lease, row.id, value).await?, + Err(error) => { + store + .fail_stage(lease, row.id, &format!("{error:#}"), RETRY_DELAY) + .await?; + return Err(error); + } + } + return Ok(()); + } + bail!( + "real handler {} is not implemented in this account-cleanup PR", + row.stage + ); } match row.stage.as_str() { "purge_media" => dummy_action(store, lease, row, options, "would purge user media").await, @@ -122,7 +169,7 @@ async fn purge_content( }, ExecutionMode::Delete, Some((lease, row.id)), - &mut std::io::stdout(), + &mut std::io::stderr(), ) .await?; // Agent cleanup is a separate handler; do not claim it is unnecessary. diff --git a/crates/buzz-deletion/src/user/worker.rs b/crates/buzz-deletion/src/user/worker.rs index 424a18265e..fff0714b66 100644 --- a/crates/buzz-deletion/src/user/worker.rs +++ b/crates/buzz-deletion/src/user/worker.rs @@ -10,16 +10,15 @@ use uuid::Uuid; use super::{handlers, transition::UserDeletionTransition}; use crate::{StageOutcome, DEFAULT_LEASE_DURATION, HEARTBEAT_INTERVAL}; -/// Shared handler controls. Demo delays and failures never invoke real deletion. +/// Real execution controls and demo-only failure/delay options. pub(super) struct RunOptions { - pub next_step: bool, pub db: Option, - // Optional preconfigured storage client; otherwise load BUZZ_S3_* at media execution. pub media: Option>, pub delete: bool, pub relay_pubkey: Option, pub batch_size: u16, pub max_items: u32, + pub next_step: bool, pub fail_stage: Option, pub stage_delay: Duration, pub no_agents_in: Vec, @@ -40,6 +39,9 @@ pub(super) async fn run( request.entity_type ); } + if !request.target.starts_with("demo:") && (!options.delete || options.db.is_none()) { + bail!("real workflow execution requires --delete and a database"); + } let Some(lease) = store.claim(id, owner, DEFAULT_LEASE_DURATION).await? else { if store.get(id).await?.status == "completed" { return Ok(0); @@ -153,6 +155,10 @@ async fn run_stage_with_heartbeat( #[path = "worker_postgres_tests.rs"] mod postgres_tests; +#[cfg(test)] +#[path = "account_worker_postgres_tests.rs"] +mod account_postgres_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/buzz-deletion/src/user/worker_postgres_tests/fixture.rs b/crates/buzz-deletion/src/user/worker_postgres_tests/fixture.rs index 4f2fad6284..6c4ca72e9c 100644 --- a/crates/buzz-deletion/src/user/worker_postgres_tests/fixture.rs +++ b/crates/buzz-deletion/src/user/worker_postgres_tests/fixture.rs @@ -28,7 +28,7 @@ impl Fixture { delete: true, relay_pubkey: None, batch_size: 100, - max_items: 1_000_000, + max_items: 100_000, next_step: false, fail_stage: None, stage_delay: Duration::ZERO, @@ -89,6 +89,33 @@ pub(super) async fn fixture() -> Fixture { .await .unwrap(); + // The real gate is not implemented. Supply its fixture prerequisite through + // the same storage API, then exercise real media dispatch and retry. + let lease = store + .claim(request.id, "fixture", DEFAULT_LEASE_DURATION) + .await + .unwrap() + .unwrap(); + let transition = UserDeletionTransition::new(&store); + let NextStage::Stage(gate) = transition.get_next_stage(&lease, None).await.unwrap() else { + panic!("expected gate") + }; + assert_eq!(gate.stage, "gate_user"); + store.start_stage(&lease, gate.id).await.unwrap(); + store + .save_stage_success(&lease, gate.id, serde_json::json!({"fixture": true})) + .await + .unwrap(); + let NextStage::Stage(media) = transition + .get_next_stage(&lease, Some(gate.id)) + .await + .unwrap() + else { + panic!("expected media") + }; + assert_eq!(media.stage, "purge_media"); + store.release(&lease).await.unwrap(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let endpoint = format!("http://{}", listener.local_addr().unwrap()); let storage = Arc::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 d6a1326306..cc56626fd2 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 @@ -1,43 +1,12 @@ +use super::media_fixture::fixture; use super::*; use std::sync::atomic::Ordering; #[tokio::test] #[ignore = "requires Postgres"] async fn gate_then_media_requires_delete_and_retries_storage_failure_before_communities() { - let fixture = media_fixture::fixture().await; + let fixture = fixture().await; let (store, id) = (&fixture.store, fixture.id); - // The real gate is not implemented. Refuse it before touching storage. - let error = run( - store, - id, - "gate-check", - &fixture.options(), - &CancellationToken::new(), - ) - .await - .unwrap_err(); - assert!(error - .to_string() - .contains("real handler gate_user is not implemented")); - assert_eq!(fixture.requests.load(Ordering::SeqCst), 0); - let lease = store - .claim(id, "gate-fixture", DEFAULT_LEASE_DURATION) - .await - .unwrap() - .unwrap(); - let NextStage::Stage(gate) = UserDeletionTransition::new(store) - .get_next_stage(&lease, None) - .await - .unwrap() - else { - panic!("expected gate") - }; - store.start_stage(&lease, gate.id).await.unwrap(); - store - .save_stage_success(&lease, gate.id, serde_json::json!({"fixture": true})) - .await - .unwrap(); - store.release(&lease).await.unwrap(); let read_only = RunOptions { delete: false, ..fixture.options() @@ -47,7 +16,7 @@ async fn gate_then_media_requires_delete_and_retries_storage_failure_before_comm .unwrap_err(); assert!(error .to_string() - .contains("media deletion requires --delete")); + .contains("real workflow execution requires --delete")); let paused = store.inspect(id).await.unwrap(); assert_eq!(paused.stage_history.len(), 2); let gate = serde_json::to_value(&paused.stage_history[0]).unwrap(); diff --git a/crates/buzz-deletion/src/user/workflow.rs b/crates/buzz-deletion/src/user/workflow.rs index a41108a9dc..469d8f4910 100644 --- a/crates/buzz-deletion/src/user/workflow.rs +++ b/crates/buzz-deletion/src/user/workflow.rs @@ -43,9 +43,19 @@ const RULES: &[Rule] = &[ Rule { name: "purge_content", community_scope: true, - allowed: &[Decision::Stage("purge_agents"), Decision::CommunityComplete], + allowed: &[ + Decision::Stage("purge_account"), + Decision::Stage("purge_agents"), + Decision::CommunityComplete, + ], decide: after_purge_content, }, + Rule { + name: "purge_account", + community_scope: true, + allowed: &[Decision::Stage("purge_agents")], + decide: |_| Ok(Decision::Stage("purge_agents")), + }, Rule { name: "purge_agents", community_scope: true, @@ -57,7 +67,7 @@ const RULES: &[Rule] = &[ fn after_purge_content(result: &Value) -> Result { // Real content cleanup leaves account and agent cleanup to later stages. if result["account_erasure_complete"] == false { - return Ok(Decision::Stage("purge_agents")); + return Ok(Decision::Stage("purge_account")); } // Demo execution retains its saved, simulated agent-routing result. match result["has_agents"].as_bool() { @@ -242,11 +252,11 @@ mod tests { for (result, expected) in [ ( serde_json::json!({"content": {}, "account_erasure_complete": false}), - Decision::Stage("purge_agents"), + Decision::Stage("purge_account"), ), ( serde_json::json!({"account_erasure_complete": false, "has_agents": false}), - Decision::Stage("purge_agents"), + Decision::Stage("purge_account"), ), ( serde_json::json!({"dummy": true, "has_agents": true}), diff --git a/crates/buzz-relay/src/handlers/side_effects.rs b/crates/buzz-relay/src/handlers/side_effects.rs index e402f469c4..02cf310a60 100644 --- a/crates/buzz-relay/src/handlers/side_effects.rs +++ b/crates/buzz-relay/src/handlers/side_effects.rs @@ -14,7 +14,7 @@ use buzz_core::kind::{ KIND_NIP43_MEMBERSHIP_LIST, KIND_REACTION, KIND_THREAD_SUMMARY, KIND_VERIFIED_PROFILE, }; use buzz_core::StoredEvent; -use buzz_db::channel::{MemberRecord, MemberRole}; +use buzz_db::channel::{group_members_tags, MemberRecord, MemberRole}; use super::channel_authz::{self, ChannelAuthzError, PutUserDecision, RemoveOtherDecision}; use super::event::dispatch_persistent_event; @@ -1603,37 +1603,6 @@ async fn emit_addressable_discovery_event( Ok(()) } -/// Tags that identify the channel on every relay-signed group-state event: -/// the channel type `t` first, then one `t` per label, then the creator `P`. -fn group_state_identity_tags( - identity: &buzz_db::channel::ChannelIdentity, -) -> anyhow::Result> { - Ok(buzz_core::channel::group_state_identity_tags( - &identity.channel_type, - &identity.labels, - &identity.created_by, - )?) -} - -fn group_members_tags( - group_id: &str, - identity: Option<&buzz_db::channel::ChannelIdentity>, - members: &[MemberRecord], -) -> anyhow::Result> { - let mut tags: Vec = Vec::with_capacity(members.len() + 3); - tags.push(Tag::parse(["d", group_id])?); - if let Some(identity) = identity { - tags.extend(group_state_identity_tags(identity)?); - } - for member in members { - let pubkey_hex = hex::encode(&member.pubkey); - // NIP-29 convention: ["p", pubkey, relay_url, role]. Empty relay_url - // because the canonical relay is implicit (this event is signed by it). - tags.push(Tag::parse(["p", &pubkey_hex, "", &member.role])?); - } - Ok(tags) -} - async fn store_group_members_event( state: &Arc, member_snapshot: &mut buzz_db::channel::LockedMemberSnapshot, @@ -1728,14 +1697,11 @@ pub async fn emit_group_discovery_events( KIND_NIP29_GROUP_ADMINS, &relay_pubkey_hex, |channel, members| { - let mut tags: Vec = vec![Tag::parse(["d", &group_id])?]; - tags.extend(group_state_identity_tags(&channel.identity())?); - // The snapshot already scoped `members` to `GROUP_ADMIN_ROLES`. - for m in members { - let pubkey_hex = hex::encode(&m.pubkey); - tags.push(Tag::parse(["p", &pubkey_hex, &m.role])?); - } - Ok(tags) + Ok(buzz_db::channel::group_admins_tags( + &group_id, + &channel.identity(), + members, + )?) }, ) .await?; diff --git a/docs/operator-user-account-cleanup.md b/docs/operator-user-account-cleanup.md new file mode 100644 index 0000000000..10147496f8 --- /dev/null +++ b/docs/operator-user-account-cleanup.md @@ -0,0 +1,143 @@ +# Offline account cleanup + +`buzz-admin user-deletions account-batches` previews or deletes supported account +records. Preview is the default. These are operator commands against the selected +`DATABASE_URL`; stop relay instances and external writers before capturing scope +and keep them stopped through deletion. The command does not stop them for you. + +## Select communities and preview current agents + +```sh +buzz-admin user-deletions account-scope --pubkey "$USER_PUBKEY" > account-scope.json +buzz-admin user-deletions account-batches --scope-file account-scope.json \ + --actor "$OPERATOR_PUBKEY" --read-only +buzz-admin user-deletions account-batches --scope-file account-scope.json \ + --actor "$OPERATOR_PUBKEY" --delete +``` + +The file selects the human and communities. Its agent keys are only a snapshot: +every preview, delete and retry fetches the current direct agents again within +each selected community. Transferred or missing ownership excludes an old agent; +newly assigned agents are included. It is an explicit offline operator input, not +a signed workflow approval. Scope capture reads one database +snapshot without writing progress, source data or caches. It includes the human +in **every stored community**, so former membership and a lack of membership do +not hide residue. It also includes agents recorded as owned by that human in +each community. Agent ownership in one community does not prove ownership in +another community or exclusive ownership of deployment-global records. + +The human's global pass runs even when there are no communities. Global agent +records remain retained until their ownership can be established; they are not +silently selected from a community-scoped owner link. If explicit ownership has +been established separately, the single-key global command below is available. + +A current target set containing an owner membership is refused before any mutation. +Resolve the owned-community handoff first. Scope generation is bounded to 1,000 +communities and 10,000 total human/agent entries; exceeding either limit fails +without returning a partial scope. The scope file is limited to 4 MiB. + +## Explicit smaller scopes + +```sh +# One human and their current direct agents in one community; no global work. +buzz-admin user-deletions account-batches --pubkey "$SUBJECT_PUBKEY" \ + --community "$COMMUNITY_ID" --read-only + +# Explicit deployment-wide authority; --actor identifies the audit actor. +buzz-admin user-deletions account-batches --pubkey "$SUBJECT_PUBKEY" \ + --global --actor "$OPERATOR_PUBKEY" --read-only +``` + +Replace `--read-only` with `--delete` to execute. `--print-only` is another preview +spelling. The modes conflict rather than letting one silently override another. +Global mode and community mode are mutually exclusive. + +| Scope | Supported operations | +| --- | --- | +| Community | Target-owned tokens, created invitations, all channel/community memberships (including removed rows), policy acceptances, allowlist entries, read frontiers and read-account rows. Existing nullable attribution clears preserve other owners' records and revocation/removal state. | +| Community feedback | Delete the target's submitted feedback in that community, including its body and tags. | +| Personal events | Delete all stored versions, including soft-deleted revisions, of directly authored kinds **3, 10000, 10001, 10002, 10003, 10030, 30000, 30003, 30315, 30078**. These cover contacts, mute/pin/bookmark/follow lists, relay preferences, personal emoji lists, status and application/read state. | +| Personal-event copies | Before deleting source events, delete matching mention-index rows, push-match jobs, push-wake outbox rows, listener outbox rows and delivery logs in the same community. Other people's signed references and reactions are preserved. | +| Global | Delete the selected key's database operator/moderator role, listener registrations in either listener or target position, and submitted feedback across communities and with NULL community. | + +Role revocation and its audit row commit together using the existing roster +lock and last-operator guard. This offline command conservatively requires a +surviving database operator; it cannot prove another relay's configuration. +Known local `RELAY_OPERATOR_PUBKEYS` / owner-fallback authority blocks deletion. +Absence from the CLI's environment is **not** proof that deployed configuration +has been cleared. Configuration-backed privileges must be removed separately. +Other principals' `added_by` attribution and prior audit history remain intact. + +## Saved channel lists + +Deletion with channel memberships requires `BUZZ_RELAY_PRIVATE_KEY`, set to the +existing serving relay's signing key. Preview requires no key. A missing key or +one that disagrees with current affected channel lists fails before cleanup +starts, including before the global pass of a saved scope. + +Each membership removal runs in its own admitted transaction, behind the same +replacement and membership locks as the relay. It rebuilds and signs kinds +39000 (channel details, including DM participants), 39001 (administrators), and +39002 (members) from the surviving rows, and commits all three with the removal. +A failed write or interrupted transaction saves neither the removal nor its new +lists. Superseded signed events remain historical records; their payloads and +signatures are not edited. For an already deleted or missing channel, remaining +current discovery heads are retired instead of creating new ones. + +The command processes these transactions sequentially. Human and agent passes +can revisit a shared channel; each committed list describes the current rows. +No background worker, notification, or new network event is involved. Open apps +fetch the corrected lists when member data is refreshed or reloaded. This does +not invalidate live sessions or authorize online account deletion; the existing +writer-stop requirement still applies outside controlled testing. +Lists left stale by an older, already completed deletion need a separate repair: +without the membership rows, this command cannot rediscover those channels. + +## Progress and retry + +`--batch-size` bounds each transaction to 1–100 selected row operations. +`--max-items` bounds an invocation to 1–1,000,000 operations, across all keys and +communities when using a scope file. A role revocation also writes one audit row +atomically. Each membership removal also writes up to three signed lists and +their mention indexes; these derived writes are not counted in the selected-row +budget. Preview marks those batches with `rebuild_saved_channel_lists`. +Each proposed batch is printed before mutation; `batch_committed` +appears only after commit. Output failure before mutation rolls that batch back. + +Exit 0 means the supported selectors were exhausted; exit 2 means the row budget +was reached; other failures return an error. A scope ending exactly on its budget +may conservatively return 2 if later scopes have not been inspected. Rerun the +same command: it fetches current direct agents and selects remaining rows. It +does not append another audit entry for an already removed role. Every batch +checks the ownership set again and locks the matching ownership rows through +commit. A changed set stops the run; retry fetches it again. A final ownership +check also prevents reporting completion with a changed set. These checks do +not replace the requirement to stop writers. Keep `users.agent_owner_pubkey` +records until all dependent handlers have finished; account cleanup retains them. +Preview uses read-only transactions; a multi-scope preview uses one snapshot per +scope. The offline writer-stop requirement makes those observations stable. + +## Deliberate limits + +See [the retention decisions](operator-user-account-retention.md) for records we +keep. The start output distinguishes retained replay protection from deferred +profile work. Replay watermark deletion is not a missing feature. + +This command does not remove historical signed membership lists or +relay-signed membership notices, infer device ownership, or prove repository +owner/delegated access has been revoked. It does not delete shared emoji sets, +profiles, messages, repository events or unknown personal event kinds. Those +require their named handler or an attribution/reconciliation implementation. +Target notification subscriptions and push leases belong to content cleanup; +capture any device attribution before that handler removes the source links. + +The existing `archived_identities.replaced_by` clear is still present; moving it +belongs to the profile handoff. The workflow adapter uses its approved human/community inputs as the discovery +root and invokes this same handler on each retry. Agents are direct children of +that human only; their own agents are not recursively included. Deployment-global +cleanup is never inferred from a community stage. Final coordinator integration and independent verification remain separate. +Every result therefore keeps **`account_erasure_complete: false`**. + +This is application code over existing tables: no schema migration, backfill, +trigger, function or foreign key is added. Normal serving behavior and existing +operator API calls retain their existing database schema contract. diff --git a/docs/operator-user-account-retention.md b/docs/operator-user-account-retention.md new file mode 100644 index 0000000000..8fb856b316 --- /dev/null +++ b/docs/operator-user-account-retention.md @@ -0,0 +1,36 @@ +# Account cleanup: retained records and boundaries + +Account cleanup removes attributable credentials, access and personal account +records. It does not mean every reference to an identity disappears. Where +ownership or treatment is uncertain, preserve the record and report the gap. +Do not infer permission to delete another person's data from a matching key. + +| Records | Treatment | +| --- | --- | +| Shared channel creator attribution | Keep `channels.created_by`. Channel content belongs to content cleanup; account cleanup removes the target's membership. | +| Repositories, Git history and routing | Keep repositories, history, name mappings and required owner references. Do not automatically transfer repositories or make them read-only for other users. Retaining a routing reference is not proof that the target's access has been revoked. | +| Other people's role provenance | Keep non-null `relay_operators.added_by` on surviving roles. Removing the target's own role is separate. | +| Moderation and enforcement | Keep bans, reports, moderation actions, admin action history and rate-limit history, including identifying keys and notes. Pending actions and copied payloads still require review before claiming complete access revocation or erasure. | +| Audit history | Keep operator audit and hash-chained audit history intact. Record new role revocations in the normal audit trail. | +| Shared device registrations | Keep registrations used by other accounts. Delete only with proven exclusive ownership; preserve and report uncertain ownership. Relay identity keys and client installation strings do not establish gateway ownership. | +| Shared signed membership lists | Rebuild current member/admin/metadata lists using the existing relay signer, atomically with each channel membership removal. Preserve superseded historical events and creator attribution. Never edit a signed payload in place. | +| Multi-subject commands and membership notices | Preserve; attribution and historical-message removal remain separate. | +| Deletion evidence and replay protection | Keep deletion requests, approvals, inventories, stage history, fences and replay watermarks. Watermark removal is not unfinished cleanup. | + +These are explicit retention exceptions, not assertions of anonymous data. +Other people's signed references can continue to identify the deleted key. +Retaining a record must never be used to claim the deleted identity has lost +authority: repository owner checks, config-backed operator roles and live +sessions need separate enforcement and verification. + +Profile rows, profile events, managed-agent definitions and archived identities +belong to profile cleanup. Independent leftover-data verification and final +coordinator wiring belong to the verifier change. The existing account command +must keep reporting `account_erasure_complete: false` while those prerequisites +and the remaining account work are incomplete. + +For supported selectors and runnable commands, see [offline account cleanup](operator-user-account-cleanup.md). + +All deletion commands run offline with relay and external writers stopped. +Preview is read-only. A per-community invocation must not silently mutate +deployment-global privileges or registrations. diff --git a/scripts/run-tests.sh b/scripts/run-tests.sh index 659ff9cf3e..170344edac 100755 --- a/scripts/run-tests.sh +++ b/scripts/run-tests.sh @@ -136,6 +136,11 @@ run_unit_tests() { run_test_step "buzz-workflow unit tests" \ cargo test -p buzz-workflow --lib -- --nocapture + # Deletion workflow/unit tests; Postgres cases remain ignored here. + # Mirrors the nextest path in `just test-unit`. + run_test_step "buzz-deletion unit tests" \ + cargo test -p buzz-deletion --lib -- --nocapture + # Keep the relay-to-agent trust-boundary regressions in the fallback path # when cargo-nextest is unavailable. run_test_step "buzz-acp tests" \