Files
buzz/crates/buzz-admin/tests/postgres_user_account_batches.rs
ravarora2 8fb0de8d53 Clean up account records and refresh member lists (#9364)
## Summary

Add bounded, resumable cleanup for a user’s account records and their
current direct agents in each selected community. Preview prints the
proposed changes without writing; deletion uses the same selectors
through the command and workflow handler.

Each run and retry discovers agent ownership again. An agent owned by
Alice in one community and Bob in another is cleaned only in Alice’s
community. Ownership changes stop the current run, and ownership rows
remain available for retries and later handlers.

Membership removal rebuilds and signs the current channel lists and
community roster in the same transaction as each removal. A failed
roster write rolls back that membership removal. The command requires
the existing relay signing key when channel or community memberships are
present, including users with no channel memberships. Preview does not
require a key.

The relay, account cleanup and admin reconciliation share the kind
39001/39002 tag builders in `buzz-db`. They preserve the existing
identity tags, roster order and role positions. Regular unit-test runs
now include `buzz-deletion` through both nextest and the Cargo fallback.

**Channel ownership policy:** deletion may remove the last channel
owner, including when the human and their agents are all owners. The
channel, messages and surviving members remain. A surviving admin can
manage the channel and grant ownership. If no owner or admin remains,
members can continue normal use, but management recovery requires
operator intervention on request. Cleanup does not require a channel
ownership handoff or assign a replacement owner. The separate
community-owner restriction remains.

The content handler now on main advances to account cleanup before the
remaining agent stage. Content and account workflow progress goes to
stderr so stdout remains one JSON inspection document. The direct
account command retains NDJSON stdout. Nullable attribution updates use
explicit table and SET clauses so the source-policy guard can inspect
them.

The handler covers credentials, memberships, read progress, supported
personal events and their copies, feedback, and explicit global
listener/database-role cleanup. It retains shared records and historical
signed lists. Scope files select the human and communities; saved agent
keys do not authorize deletion.

This remains an offline operator feature: stop relay and external
writers before deletion. It does not revoke already-connected sessions.
Coordinator integration, remaining handlers and final erasure
verification are separate; results always report
`account_erasure_complete: false`. The real account workflow still stops
at an unimplemented successor.

### Related issue

Replaces the account scope of #9354 and #9355 with one focused PR. Those
earlier PRs remain intact for reference. Agent cleanup belongs within
the business handlers; this change does not integrate the historical
standalone agent stage in #8959.

### Testing

Exercised the real preview and delete commands in an isolated local
relay/database with Alice disconnected and Bob’s desktop app open.
Preview left the normalized database dump unchanged. Deletion checks
covered all 101 tables and all 30 affected channels; 168 newly signed
list events verified. Bob refreshed the member dialog and saw Bob, B1
and Carol, then successfully sent and read a message. A1’s membership in
the community where Bob owns it remained intact.

The live CLI and desktop evidence above predates the latest follow-up.
Independent end-to-end checks at `d45759df2` also verified unchanged
preview data, signed channel/community lists after deletion, signing-key
preflight, and workflow JSON stdout. The shared-builder follow-up was
source-reviewed and formatted; local builds, tests and commit/push hooks
were skipped at the author’s request. Validation of the new revision and
a repeat of the signed-list end-to-end check are pending. Human testing
remains pending.

For human verification, use an isolated database and its relay signing
key. Preview a community-only member, confirm no writes, then delete and
verify the current kind 13534 roster omits them. Run an approved
account-stage fixture with `user-deletions run <id> --delete
--next-step`; the entire stdout must parse as one JSON document, with
batch progress on stderr.

Generated with Codex

---------

Signed-off-by: Ravneet Arora <rarora@squareup.com>
Signed-off-by: soup <757a365d4ee72aedf003a39cd856b16b49a3b940a42fe00402b8f80fbc40e730@buzz.block.builderlab.xyz>
Co-authored-by: soup <757a365d4ee72aedf003a39cd856b16b49a3b940a42fe00402b8f80fbc40e730@buzz.block.builderlab.xyz>
Co-authored-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz>
2026-11-17 15:11:25 -05:00

271 lines
8.8 KiB
Rust

//! 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<Value> {
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::<Vec<_>>()
};
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<String>| {
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");
}