mirror of
https://github.com/block/buzz.git
synced 2026-11-24 02:02:07 +00:00
Add community-scoped user and agent profile cleanup (#9580)
## Summary
Content, account and media cleanup leave profile records behind. Add
`buzz-admin user-deletions profile-batches` to preview or delete those
records in one community. Preview is the default; explicit `--delete`
applies bounded, retryable transactions.
Every run and retry discovers the human’s current direct agents in that
community. Ownership elsewhere cannot authorize deletion here. If Alice
owns an agent in A but Bob owns it in B, deleting Alice in B preserves
that agent. Each write batch locks and rechecks ownership. All profile
data is removed before identity rows, so an interrupted run resumes
without saved agent keys. The command no longer accepts
`--agent-pubkey`.
The handler removes profile/configuration events and projections,
rebuilds shared archive snapshots with valid signatures, and finally
removes identity rows. Repository announcements/state (30617/30618) and
name mappings remain intact without blocking identity removal; other
authored content still requires prior cleanup. Unresolved dependencies,
changed sources, untrusted signers or excessive plans stop deletion.
This includes historical `replaced-by` references in archive requests
and deltas, even after unarchive removes the current archive row. See
[operator instructions and verification steps](docs/profile-cleanup.md).
Writers must be stopped. Coordinator integration, online admission
fencing, media objects, client caches and final account-erasure
verification remain separate. The command always reports
`account_erasure_complete: false`.
### Related issue
Fixes #9576. Continues the standalone handler pattern from #9363
(content) and #9364 (account). This is an independent PR against main.
### Testing
The latest correction adds a PostgreSQL regression that runs content
cleanup followed by profile preview/delete/retry for human and agent
repository owners. It checks unchanged repository events, mentions, name
mappings and other-community data, and verifies ordinary content still
blocks profile deletion. The merge of main brings in `buzz-deletion
--lib` coverage in the CI unit lane and its fallback, covering the
preview-default parser test without duplicate runs. Account, content,
media and profile command dispatch are all preserved. The
archive-history documentation also now distinguishes planning errors
from printed blockers.
The latest main merge includes the shared dependency-policy correction
from #9609 and the content cleanup lock fix from #9615. On `54bd50299`,
PostgreSQL CI passed 1647 tests and failed 18 because content cleanup
still called the retired SQL lock-key function; this also blocked the
new content→profile regression. The merged upstream fix uses the
existing Rust-built key for both the cleanup lock and the test blocker.
Local test suites and hooks remain skipped at the owner’s request. CI
and review of the updated head are pending. The results below apply to
earlier revisions.
At `92aa9c216`, exercised the rebuilt `buzz-admin` against signed
archive/unarchive events stored in disposable PostgreSQL:
- For kinds 9035 and 8002, test a historical `replaced-by` reference to
the human and then to their owned agent after unarchive.
- Run `profile-batches --pubkey <human> --community <A> --relay-pubkey
<relay>` in preview and `--delete` modes. Both refuse the unresolved
reference; full table dumps remain unchanged.
- Keep that history only in community B. Cleanup in A succeeds,
preserves B, and selects zero work on retry.
- Delete the archive subject in B. Its history is removed while the
replacement identities remain intact.
All four scenarios passed. These are signed database fixtures exercised
through the real CLI; they do not claim live relay admission. The
correction also merges main and preserves content, media and profile
command dispatch.
The initial full database run passed 880/881 tests: the new request
fixture lost its required self-`p` tag during signing. Commit
`ff6689386` preserves that tag; all ten profile regressions now pass.
Further local checks and pre-push hooks were skipped at the owner’s
explicit request. The full corrected database suite has not been rerun;
GitHub CI will validate the new head. At `ff6689386`, the production
code matched the CLI-tested revision; the repository-retention
correction above is newer.
Previous ownership validation follows:
At `090d2a1cf`, exercised the rebuilt `buzz-admin` binary against a
disposable PostgreSQL fixture:
- Run `user-deletions profile-batches --pubkey <human> --community <A>`:
preview left table exports unchanged and selected four profile/identity
mutations.
- Repeat with `--delete --batch-size 2`: all four mutations committed;
retry selected zero work.
- Use the same human and agent keys in another community, with the agent
owned by someone else: only the human was selected, and the agent
remained intact.
This fixture uses placeholder profile signatures and validates
database/CLI behavior. It does not claim live signed-event admission.
The earlier live relay and Desktop results below cover the previous
revision.
Independent agent review covered the previous ownership correction. A
later review found the historical replacement-reference bug; the
historical-reference correction addresses that finding. Fresh review of
this revision is still required. Human command verification has not been
recorded; it is not claimed by the agent-run checks. Follow the local
verification steps in `docs/profile-cleanup.md`; preview must leave data
unchanged, deletion must preserve other-community records, and retry
must select zero work.
<details>
<summary>Historical validation at fdf8a8363, before the ownership
correction</summary>
These records are retained from the earlier PR description. They do not
validate the current revision. The saved-agent-key retry below describes
the old interface, which this update removes.
- `cargo test -p buzz-db -p buzz-deletion -p buzz-admin`: passed at
`fdf8a8363` (298 tests, with PostgreSQL tests in the separate lane).
- `cargo clippy -p buzz-db -p buzz-deletion -p buzz-admin --all-targets
-- -D warnings`: passed.
- Full PostgreSQL lane for those three packages: **814/818 passed**,
including all five new profile tests. Four unchanged infrastructure
tests failed: reader-pool startup, a `postgres://`-only test given a
`postgresql://` URL, a one-second partition-lock timing assertion (1.55
seconds), and size-one matcher pool startup. The URL spelling has been
corrected for future runs; the full lane has not yet been rerun. The run
experienced heavy host contention.
- Actual `buzz-admin` command against a separate disposable SQL fixture:
default preview, `--print-only`, and `--read-only` left all table
exports unchanged; `--delete` removed four selected rows;
survivor/second-community data remained; retry selected zero rows. This
is database/CLI evidence, not live relay acceptance.
- Workspace Rust clippy and desktop static checks passed. `just ci`
initially stopped at mobile formatting because the fresh worktree lacked
Flutter package configuration; dependencies were installed and the retry
remains incomplete. The long-running local pre-push run was stopped to
publish the draft at the author’s request; incomplete gates are not
claimed as passing.
- Isolated live relay at `fdf8a8363`: 22 signed client events accepted
across two communities; WebSocket authentication established four
agent-owner links. All three preview forms left all 67 public tables
unchanged. `--delete --batch-size 2` removed eight selected source
events, four mention rows, one archive row and two identity rows, and
inserted one independently verified survivor-only archive snapshot. All
other rows matched exactly; retry selected zero work.
- Eight refusal cases left every table unchanged. A real process kill
after a committed batch, followed by retry with saved agent keys,
produced the exact expected result. Separate signed SQL fixtures covered
kind 30382, verified heads and historical kind 30179; these do not claim
live issuer-backed admission.
- Independent restart checks passed: target profiles stayed absent from
events, search and NIP-05; the other community was preserved; the
surviving user could publish and read a profile update. A separate
replay clone confirmed the boundary: replaying the original target
profile recreated its user row, and a fresh profile was accepted too.
Permanent erasure requires external admission/write fencing.
- Native Desktop experiment: relay/admin `fdf8a8363`, `buzz-app`
`859c9953a` with isolated app storage and a local TLS configuration.
Seed a survivor-owned conversation, open Alice and her agent's profiles,
then run `profile-batches --delete --batch-size 2` while app and relay
remain running. Preview selected 17 mutations across nine batches
without changing any of 67 tables. Deletion removed ten source events,
four associated mention rows and two users, then inserted one validly
signed survivor-only archive snapshot. Every other row, including eight
survivor events and community B, matched exactly. Retry did zero work.
- Desktop observations: fresh signed relay reads returned no target
profiles/events/NIP-05 in A; B and the survivor conversation remained
readable. Bob updated his profile through the API and sent a reply
through the native composer, with signed relay readback and visible
receipt. Cached target details remained in the open profile panel,
reopened search and after an app-page reload/reconnect. This does not
erase client caches or prove safety under concurrent target writes; the
stopped-writer contract remains.
- At that earlier revision, the PR was draft pending human command
verification. Agent testing does not satisfy the repository's
human-testing requirement, and this command does not certify online
erasure.
</details>
Generated with Codex
---------
Signed-off-by: Ravneet Arora <rarora@squareup.com>
Co-authored-by: dessert <7d616e7e143e5d408159614dccff1371350a1c1bd36c8de838a45ece5aca0aca@buzz.block.builderlab.xyz>
Co-authored-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz>
This commit is contained in:
@@ -8,6 +8,8 @@ pub mod content_batches;
|
||||
mod discovery;
|
||||
mod inventory;
|
||||
mod media;
|
||||
/// Standalone, offline profile cleanup with read-only preview.
|
||||
pub mod profile_batches;
|
||||
mod requests;
|
||||
pub use discovery::normalize_user_deletion_pubkey;
|
||||
pub use inventory::UserDeletionInventory;
|
||||
|
||||
278
crates/buzz-db/src/store/user_deletion/profile_batches/events.rs
Normal file
278
crates/buzz-db/src/store/user_deletion/profile_batches/events.rs
Normal file
@@ -0,0 +1,278 @@
|
||||
use super::*;
|
||||
use chrono::{DateTime, Utc};
|
||||
use nostr::{Event, EventBuilder, Kind, Tag, Timestamp};
|
||||
use sqlx::Row;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(super) struct Snapshot {
|
||||
signer: String,
|
||||
time: u64,
|
||||
survivors: Arc<Vec<String>>,
|
||||
}
|
||||
pub(super) struct Selected {
|
||||
pub id: Vec<u8>,
|
||||
pub key: Value,
|
||||
pub fingerprint: String,
|
||||
pub snapshot: Option<Snapshot>,
|
||||
}
|
||||
|
||||
fn subject(tags: &Value, name: &str) -> Result<String> {
|
||||
let all = tags
|
||||
.as_array()
|
||||
.ok_or_else(|| invalid("profile tags are not an array"))?;
|
||||
let tagged: Vec<_> = all
|
||||
.iter()
|
||||
.filter(|t| t.get(0).and_then(Value::as_str) == Some(name))
|
||||
.collect();
|
||||
if tagged.len() != 1 {
|
||||
return Err(invalid(format!(
|
||||
"profile requires exactly one {name} subject"
|
||||
)));
|
||||
}
|
||||
let value = tagged[0]
|
||||
.get(1)
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| invalid("missing profile subject"))?;
|
||||
if value.len() != 64 || !value.bytes().all(|c| c.is_ascii_hexdigit()) {
|
||||
return Err(invalid("malformed profile subject"));
|
||||
}
|
||||
normalize_user_deletion_pubkey(value)
|
||||
}
|
||||
|
||||
pub(super) async fn select(
|
||||
conn: &mut PgConnection,
|
||||
scope: &Scope,
|
||||
max: u32,
|
||||
) -> Result<Vec<Selected>> {
|
||||
// Scope before payload inspection. Case-insensitive subject comparison covers historical hex.
|
||||
// Historical replacement references survive unarchive removing the canonical row.
|
||||
// The statement budget bounds the fallback tag scan; no new schema is required.
|
||||
let candidate_sql="SELECT id,created_at,kind,encode(pubkey,'hex') AS author,channel_id,
|
||||
CASE WHEN pg_column_size(tags)<=65536 THEN tags END AS tags,
|
||||
jsonb_build_object('id',id,'created_at',created_at) AS key,encode(sha256(convert_to(to_jsonb(e)::text,'UTF8')),'hex') AS fingerprint
|
||||
FROM events e WHERE community_id=$1 AND kind IN (0,10100,30177,30179,30382,9035,9036,8002,8003,13535)
|
||||
AND (pubkey=ANY($2::bytea[]) OR EXISTS(SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(tags)='array' THEN tags ELSE '[]'::jsonb END) tag
|
||||
WHERE (tag->>0 IN ('p','d') AND lower(tag->>1)=ANY($3::text[])) OR (tag->>0='consent' AND lower(tag->>2)=ANY($3::text[]))
|
||||
OR (kind IN (9035,9036,8002,8003) AND tag->>0='replaced-by' AND lower(tag->>1)=ANY($3::text[]))))
|
||||
ORDER BY created_at,id LIMIT $4";
|
||||
// Bound payload memory before materializing candidate tags. The query remains read-only.
|
||||
let budget_sql = format!("SELECT count(*) AS count, COALESCE(sum(pg_column_size(tags)),0)::bigint AS bytes FROM ({candidate_sql}) candidates");
|
||||
let budget = sqlx::query(sqlx::AssertSqlSafe(budget_sql))
|
||||
.bind(scope.community)
|
||||
.bind(&scope.bytes)
|
||||
.bind(&scope.targets)
|
||||
.bind((i64::from(max) + 1).min(65_537))
|
||||
.fetch_one(&mut *conn)
|
||||
.await?;
|
||||
if budget.try_get::<i64, _>("count")? > i64::from(max).min(65_536)
|
||||
|| budget.try_get::<i64, _>("bytes")? > 32 * 1024 * 1024
|
||||
{
|
||||
return Err(invalid(
|
||||
"profile candidates exceed item or 32 MiB payload budget",
|
||||
));
|
||||
}
|
||||
let candidates = sqlx::query(candidate_sql)
|
||||
.bind(scope.community)
|
||||
.bind(&scope.bytes)
|
||||
.bind(&scope.targets)
|
||||
.bind((i64::from(max) + 1).min(65_537))
|
||||
.fetch_all(&mut *conn)
|
||||
.await?;
|
||||
if candidates.len() > max as usize {
|
||||
return Err(invalid(
|
||||
"profile candidates exceed max-items; no deletion performed",
|
||||
));
|
||||
}
|
||||
let survivors:Vec<String>=sqlx::query_scalar("SELECT pubkey FROM archived_identities WHERE community_id=$1 AND NOT(pubkey=ANY($2::text[])) ORDER BY pubkey LIMIT 10001")
|
||||
.bind(scope.community).bind(&scope.targets).fetch_all(&mut *conn).await?;
|
||||
let survivors = Arc::new(survivors);
|
||||
let mut out: Vec<Selected> = Vec::new();
|
||||
// Every replacement is strictly newer than every current snapshot from that signer.
|
||||
let mut next_time: HashMap<String, u64> = HashMap::new();
|
||||
let mut snapshot_index: HashMap<String, usize> = HashMap::new();
|
||||
for row in candidates {
|
||||
let kind: i32 = row.try_get("kind")?;
|
||||
let author: String = row.try_get("author")?;
|
||||
let tags: Value = row
|
||||
.try_get::<Option<Value>, _>("tags")?
|
||||
.ok_or_else(|| invalid("profile tags exceed 64 KiB"))?;
|
||||
let authored = scope.targets.contains(&author);
|
||||
let mut snapshot = None;
|
||||
let selected = match kind {
|
||||
0 | 10100 => authored,
|
||||
30177 | 30179 => {
|
||||
let agent = subject(&tags, "d")?;
|
||||
if authored && !scope.targets.contains(&agent) {
|
||||
return Err(invalid(
|
||||
"managed definition names an agent not currently owned in this community",
|
||||
));
|
||||
}
|
||||
if scope.targets.contains(&agent) && author != scope.human {
|
||||
return Err(invalid("managed agent definition belongs to another owner"));
|
||||
}
|
||||
authored && scope.targets.contains(&agent)
|
||||
}
|
||||
30382 => {
|
||||
let target = subject(&tags, "p")?;
|
||||
if target != subject(&tags, "d")? {
|
||||
return Err(invalid("verified profile d/p subjects disagree"));
|
||||
}
|
||||
if scope.targets.contains(&target) {
|
||||
trusted(scope, &author)?;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
9035 | 9036 => {
|
||||
let target = subject(&tags, "p")?;
|
||||
if !scope.targets.contains(&target) {
|
||||
return Err(invalid("archive request concerns a surviving identity; shared-history disposition required"));
|
||||
}
|
||||
scope.targets.contains(&target)
|
||||
}
|
||||
8002 | 8003 => {
|
||||
let target = subject(&tags, "p")?;
|
||||
if scope.targets.contains(&target) {
|
||||
trusted(scope, &author)?;
|
||||
true
|
||||
} else {
|
||||
return Err(invalid("archive delta references a target actor or replacement on a surviving identity; shared-history disposition required"));
|
||||
}
|
||||
}
|
||||
13535 => {
|
||||
trusted(scope, &author)?;
|
||||
if survivors.len() > 10_000 {
|
||||
return Err(invalid(
|
||||
"archive snapshot exceeds 10000 retained identities",
|
||||
));
|
||||
}
|
||||
let previous = if let Some(previous) = next_time.get(&author) {
|
||||
*previous
|
||||
} else {
|
||||
let max_time:Option<DateTime<Utc>>=sqlx::query_scalar("SELECT max(created_at) FROM events WHERE community_id=$1 AND kind=13535 AND pubkey=decode($2,'hex')")
|
||||
.bind(scope.community).bind(&author).fetch_one(&mut *conn).await?;
|
||||
max_time
|
||||
.map_or(0, |t| t.timestamp().max(0) as u64)
|
||||
.max(Timestamp::now().as_secs())
|
||||
};
|
||||
let time = previous
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| invalid("archive snapshot timestamp overflow"))?;
|
||||
next_time.insert(author.clone(), time);
|
||||
snapshot = Some(Snapshot {
|
||||
signer: author.clone(),
|
||||
time,
|
||||
survivors: survivors.clone(),
|
||||
});
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if selected {
|
||||
if row.try_get::<Option<Uuid>, _>("channel_id")?.is_some() {
|
||||
return Err(invalid("channel-bearing profile requires content cleanup"));
|
||||
}
|
||||
if let Some(new_snapshot) = &snapshot {
|
||||
if let Some(previous) =
|
||||
snapshot_index.insert(new_snapshot.signer.clone(), out.len())
|
||||
{
|
||||
out[previous].snapshot = None;
|
||||
}
|
||||
}
|
||||
out.push(Selected {
|
||||
id: row.try_get("id")?,
|
||||
key: row.try_get("key")?,
|
||||
fingerprint: row.try_get("fingerprint")?,
|
||||
snapshot,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
fn trusted(scope: &Scope, author: &str) -> Result<()> {
|
||||
if !scope.relays.iter().any(|r| r == author) {
|
||||
return Err(invalid("subject profile/archive event has an untrusted relay signer; supply verified --relay-pubkey"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn sign_snapshots(
|
||||
plan: &Plan,
|
||||
signer: Option<&nostr::Keys>,
|
||||
) -> Result<HashMap<String, Event>> {
|
||||
let mut out = HashMap::new();
|
||||
let Some(signer) = signer else {
|
||||
return Ok(out);
|
||||
};
|
||||
for op in &plan.ops {
|
||||
let Some(snapshot) = &op.snapshot else {
|
||||
continue;
|
||||
};
|
||||
if signer.public_key().to_hex() != snapshot.signer {
|
||||
return Err(invalid(
|
||||
"relay signing key does not match archive snapshot signer",
|
||||
));
|
||||
}
|
||||
let mut tags = vec![Tag::parse(["-"]).map_err(|_| invalid("invalid archive marker"))?];
|
||||
for p in snapshot.survivors.iter() {
|
||||
tags.push(
|
||||
Tag::parse(["p", p.as_str()]).map_err(|_| invalid("invalid archive subject"))?,
|
||||
);
|
||||
}
|
||||
let event = EventBuilder::new(Kind::Custom(13535), "")
|
||||
.tags(tags)
|
||||
.custom_created_at(Timestamp::from(snapshot.time))
|
||||
.sign_with_keys(signer)
|
||||
.map_err(|_| invalid("could not sign archive snapshot"))?;
|
||||
out.insert(op.key.to_string(), event);
|
||||
if out.len() > 64 {
|
||||
return Err(invalid("too many archive signers"));
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub(super) async fn replace_snapshot(
|
||||
tx: &mut crate::AdmittedTx,
|
||||
scope: &Scope,
|
||||
op: &rows::Operation,
|
||||
replacements: &HashMap<String, Event>,
|
||||
) -> Result<u64> {
|
||||
let event = replacements
|
||||
.get(&op.key.to_string())
|
||||
.ok_or_else(|| invalid("missing signed archive replacement"))?;
|
||||
let current: Vec<String> = sqlx::query_scalar(
|
||||
"SELECT pubkey FROM archived_identities WHERE community_id=$1 ORDER BY pubkey LIMIT 10001",
|
||||
)
|
||||
.bind(scope.community)
|
||||
.fetch_all(tx.conn())
|
||||
.await?;
|
||||
let expected: Vec<String> = event
|
||||
.tags
|
||||
.iter()
|
||||
.filter_map(|t| {
|
||||
let t = t.as_slice();
|
||||
(t.first().map(String::as_str) == Some("p"))
|
||||
.then(|| t.get(1).cloned())
|
||||
.flatten()
|
||||
})
|
||||
.collect();
|
||||
if current != expected {
|
||||
return Err(invalid(
|
||||
"archive membership changed; re-preview before snapshot replacement",
|
||||
));
|
||||
}
|
||||
// A shared event writer preserves the normal insert hooks and replica rules.
|
||||
let removed=sqlx::query("DELETE FROM events e WHERE community_id=$1 AND id=($2->>'id')::bytea AND created_at=($2->>'created_at')::timestamptz AND encode(sha256(convert_to(to_jsonb(e)::text,'UTF8')),'hex')=$3")
|
||||
.bind(scope.community).bind(&op.key).bind(&op.fingerprint).execute(tx.conn()).await?.rows_affected();
|
||||
if removed != 1 {
|
||||
return Ok(removed);
|
||||
}
|
||||
let (_, inserted) = crate::event::insert_event_in_transaction(tx, event, None).await?;
|
||||
if !inserted {
|
||||
return Err(invalid("archive replacement already exists; re-preview"));
|
||||
}
|
||||
Ok(removed)
|
||||
}
|
||||
268
crates/buzz-db/src/store/user_deletion/profile_batches/mod.rs
Normal file
268
crates/buzz-db/src/store/user_deletion/profile_batches/mod.rs
Normal file
@@ -0,0 +1,268 @@
|
||||
//! Offline profile erasure. Preview and deletion share the exact immutable plan.
|
||||
//! Writers must remain stopped until the caller's full deletion verification ends.
|
||||
use super::{normalize_user_deletion_pubkey, UserDeletionStore};
|
||||
use crate::{DbError, Result};
|
||||
use serde::Serialize;
|
||||
use serde_json::{json, Value};
|
||||
use sqlx::{Connection, PgConnection};
|
||||
use std::io::Write;
|
||||
use uuid::Uuid;
|
||||
|
||||
mod events;
|
||||
mod ownership;
|
||||
mod plan;
|
||||
#[cfg(test)]
|
||||
mod postgres_tests;
|
||||
mod rows;
|
||||
|
||||
/// Explicit scope for standalone profile preview and deletion.
|
||||
pub struct ProfileBatchOptions {
|
||||
/// Surviving community whose profiles are selected.
|
||||
pub community: Uuid,
|
||||
/// Human key as hex or npub.
|
||||
pub pubkey: String,
|
||||
/// Explicitly trusted current/historical relay signing keys.
|
||||
pub relay_pubkeys: Vec<String>,
|
||||
/// Row mutations per transaction, 1..=100.
|
||||
pub batch_size: u16,
|
||||
/// Maximum planned mutations, 1..=1,000,000; overflow makes no changes.
|
||||
pub max_items: u32,
|
||||
}
|
||||
|
||||
/// Result for this profile scope, never a claim of complete account erasure.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ProfileBatchSummary {
|
||||
/// preview_complete or delete_complete, emitted only on success.
|
||||
pub record: &'static str,
|
||||
/// Proposed or committed row mutations.
|
||||
pub items: usize,
|
||||
/// Proposed or committed transactions.
|
||||
pub batches: usize,
|
||||
/// Human and current community agents discovered for this invocation.
|
||||
pub target_pubkeys: Vec<String>,
|
||||
/// Always false; the independent final verifier owns that claim.
|
||||
pub account_erasure_complete: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Scope {
|
||||
community: Uuid,
|
||||
human: String,
|
||||
targets: Vec<String>,
|
||||
bytes: Vec<Vec<u8>>,
|
||||
relays: Vec<String>,
|
||||
}
|
||||
|
||||
struct Plan {
|
||||
scope: Scope,
|
||||
ops: Vec<rows::Operation>,
|
||||
blockers: Vec<String>,
|
||||
}
|
||||
|
||||
impl UserDeletionStore {
|
||||
/// Preview or execute a standalone profile plan with stopped writers.
|
||||
///
|
||||
/// No workflow is enabled, lease acquired or deletion journal modified.
|
||||
/// `relay_secret` is required only to replace a shared archive snapshot;
|
||||
/// it must match that snapshot's trusted signer and is never printed.
|
||||
pub async fn run_profile_batches(
|
||||
&self,
|
||||
options: &ProfileBatchOptions,
|
||||
delete: bool,
|
||||
relay_secret: Option<&str>,
|
||||
writer: &mut impl Write,
|
||||
) -> Result<ProfileBatchSummary> {
|
||||
if !(1..=100).contains(&options.batch_size) || !(1..=1_000_000).contains(&options.max_items)
|
||||
{
|
||||
return Err(invalid(
|
||||
"batch-size must be 1..100 and max-items 1..1000000",
|
||||
));
|
||||
}
|
||||
let mut conn = self.pool.acquire().await?.detach();
|
||||
// Detached connection closes on every return/cancellation; settings never leak to the pool.
|
||||
sqlx::query("SET statement_timeout='30s'")
|
||||
.execute(&mut conn)
|
||||
.await?;
|
||||
sqlx::query("SET lock_timeout='3s'")
|
||||
.execute(&mut conn)
|
||||
.await?;
|
||||
sqlx::query("SET TIME ZONE 'UTC'")
|
||||
.execute(&mut conn)
|
||||
.await?;
|
||||
let mut snapshot = conn.begin().await?;
|
||||
sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY")
|
||||
.execute(&mut *snapshot)
|
||||
.await?;
|
||||
let plan = plan::build(&mut snapshot, options).await?;
|
||||
snapshot.rollback().await?;
|
||||
line(
|
||||
writer,
|
||||
&json!({"record":"profile_batches_start", "community":options.community,
|
||||
"target_pubkeys":plan.scope.targets, "read_only":!delete,
|
||||
"blockers":plan.blockers,
|
||||
"retained":["deletion records", "replay protection", "repositories"],
|
||||
"external_work":["media objects", "client caches", "online admission and writer fencing"],
|
||||
"account_erasure_complete":false}),
|
||||
)?;
|
||||
let signer = if delete && plan.ops.iter().any(|o| o.snapshot.is_some()) {
|
||||
Some(
|
||||
nostr::Keys::parse(relay_secret.ok_or_else(|| {
|
||||
invalid("archive snapshot replacement requires BUZZ_RELAY_PRIVATE_KEY")
|
||||
})?)
|
||||
.map_err(|_| invalid("invalid relay signing key"))?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if delete && !plan.blockers.is_empty() {
|
||||
return Err(invalid(
|
||||
"profile prerequisites unresolved; see printed blockers; no changes made",
|
||||
));
|
||||
}
|
||||
// Sign before the first mutation: a missing/wrong key cannot strand a partial deletion.
|
||||
let replacements = events::sign_snapshots(&plan, signer.as_ref())?;
|
||||
let mut groups = Vec::new();
|
||||
let mut start = 0;
|
||||
let mut count = 0;
|
||||
for (index, op) in plan.ops.iter().enumerate() {
|
||||
if op.cost() > usize::from(options.batch_size) {
|
||||
return Err(invalid(
|
||||
"archive replacement needs batch-size of at least 2",
|
||||
));
|
||||
}
|
||||
if count + op.cost() > usize::from(options.batch_size) {
|
||||
groups.push(&plan.ops[start..index]);
|
||||
start = index;
|
||||
count = 0;
|
||||
}
|
||||
count += op.cost();
|
||||
}
|
||||
if start < plan.ops.len() {
|
||||
groups.push(&plan.ops[start..]);
|
||||
}
|
||||
let items: usize = plan.ops.iter().map(rows::Operation::cost).sum();
|
||||
if items > options.max_items as usize {
|
||||
return Err(invalid(
|
||||
"profile mutations exceed max-items; no changes made",
|
||||
));
|
||||
}
|
||||
let mut batches = 0;
|
||||
let mut remaining_targets = plan.scope.targets.clone();
|
||||
for (batch_index, batch) in groups.iter().enumerate() {
|
||||
line(
|
||||
writer,
|
||||
&json!({"record":"proposed_batch", "number":batch_index+1,
|
||||
"items":batch.iter().map(rows::Operation::description).collect::<Vec<_>>()}),
|
||||
)?;
|
||||
if delete {
|
||||
let mut raw = self.pool.begin().await?;
|
||||
for setting in [
|
||||
"SET LOCAL statement_timeout='30s'",
|
||||
"SET LOCAL lock_timeout='3s'",
|
||||
"SET LOCAL TIME ZONE 'UTC'",
|
||||
] {
|
||||
sqlx::query(setting).execute(&mut *raw).await?;
|
||||
}
|
||||
lock(&mut raw, &plan.scope).await?;
|
||||
let mut tx = crate::AdmittedTx::admit(
|
||||
raw,
|
||||
&crate::deletion::DeletionStore::new(self.pool.clone()),
|
||||
buzz_core::CommunityId::from_uuid(plan.scope.community),
|
||||
)
|
||||
.await?;
|
||||
ownership::recheck(tx.conn(), &plan.scope, &remaining_targets).await?;
|
||||
for op in *batch {
|
||||
rows::apply(&mut tx, &plan.scope, op, &replacements).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
for op in *batch {
|
||||
if op.table.name == "users" {
|
||||
let key = op.key["pubkey"]
|
||||
.as_str()
|
||||
.ok_or_else(|| invalid("invalid identity key"))?;
|
||||
let key = key
|
||||
.strip_prefix("\\x")
|
||||
.ok_or_else(|| invalid("invalid identity key"))?;
|
||||
if key != plan.scope.human {
|
||||
remaining_targets.retain(|p| p != key);
|
||||
}
|
||||
}
|
||||
}
|
||||
line(
|
||||
writer,
|
||||
&json!({"record":"batch_committed","number":batch_index+1,"items":batch.iter().map(rows::Operation::cost).sum::<usize>()}),
|
||||
)?;
|
||||
}
|
||||
batches += 1;
|
||||
}
|
||||
if !plan.blockers.is_empty() {
|
||||
return Err(invalid(
|
||||
"preview has unresolved prerequisites; no completion marker",
|
||||
));
|
||||
}
|
||||
if delete {
|
||||
// Original proven keys are inspection-only: removed identities must not shrink
|
||||
// final verification or become imported authority for a later invocation.
|
||||
let mut tx = conn.begin().await?;
|
||||
lock(&mut tx, &plan.scope).await?;
|
||||
ownership::recheck(&mut tx, &plan.scope, &remaining_targets).await?;
|
||||
let remaining = plan::inspect(&mut tx, plan.scope.clone(), options.max_items).await?;
|
||||
if !remaining.ops.is_empty() || !remaining.blockers.is_empty() {
|
||||
return Err(invalid(
|
||||
"profile rows or dependencies remain; cleanup did not complete",
|
||||
));
|
||||
}
|
||||
tx.commit().await?;
|
||||
}
|
||||
let summary = ProfileBatchSummary {
|
||||
record: if delete {
|
||||
"delete_complete"
|
||||
} else {
|
||||
"preview_complete"
|
||||
},
|
||||
items,
|
||||
batches,
|
||||
target_pubkeys: plan.scope.targets,
|
||||
account_erasure_complete: false,
|
||||
};
|
||||
line(writer, &summary)?;
|
||||
conn.close().await?;
|
||||
Ok(summary)
|
||||
}
|
||||
}
|
||||
|
||||
async fn lock(conn: &mut PgConnection, scope: &Scope) -> Result<()> {
|
||||
sqlx::query("SELECT pg_advisory_xact_lock_shared($1)")
|
||||
.bind(crate::deletion::SCHEMA_DESTRUCTION_LOCK_KEY)
|
||||
.execute(&mut *conn)
|
||||
.await?;
|
||||
sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))")
|
||||
.bind(crate::deletion::community_deletion_lock_key(
|
||||
buzz_core::CommunityId::from_uuid(scope.community),
|
||||
))
|
||||
.execute(&mut *conn)
|
||||
.await?;
|
||||
let active: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM communities WHERE id=$1 AND deletion_state='active' AND deleted_at IS NULL)")
|
||||
.bind(scope.community).fetch_one(conn).await?;
|
||||
if !active {
|
||||
return Err(invalid(
|
||||
"community is absent or undergoing whole-community deletion",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn invalid(message: impl Into<String>) -> DbError {
|
||||
DbError::DeletionSafety(message.into())
|
||||
}
|
||||
fn line(writer: &mut impl Write, value: &impl Serialize) -> Result<()> {
|
||||
let bytes = serde_json::to_vec(value)?;
|
||||
if bytes.len() > 2 * 1024 * 1024 {
|
||||
return Err(invalid("output exceeds 2 MiB; reduce batch-size"));
|
||||
}
|
||||
writer
|
||||
.write_all(&bytes)
|
||||
.and_then(|()| writer.write_all(b"\n"))
|
||||
.and_then(|()| writer.flush())
|
||||
.map_err(|e| invalid(format!("profile batch output failed: {e}")))
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
use super::*;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
pub(super) async fn targets(
|
||||
conn: &mut PgConnection,
|
||||
community: Uuid,
|
||||
human: &str,
|
||||
lock: bool,
|
||||
) -> Result<Vec<String>> {
|
||||
let sql = if lock {
|
||||
"SELECT pubkey FROM users WHERE community_id=$1 AND agent_owner_pubkey=decode($2,'hex') ORDER BY pubkey LIMIT 10001 FOR SHARE"
|
||||
} else {
|
||||
"SELECT pubkey FROM users WHERE community_id=$1 AND agent_owner_pubkey=decode($2,'hex') ORDER BY pubkey LIMIT 10001"
|
||||
};
|
||||
let agents: Vec<Vec<u8>> = sqlx::query_scalar(sql)
|
||||
.bind(community)
|
||||
.bind(human)
|
||||
.fetch_all(conn)
|
||||
.await?;
|
||||
let mut targets = BTreeSet::from([human.to_owned()]);
|
||||
targets.extend(agents.iter().map(hex::encode));
|
||||
if targets.len() > 10_000 {
|
||||
return Err(invalid("profile target limit exceeded (10000)"));
|
||||
}
|
||||
Ok(targets.into_iter().collect())
|
||||
}
|
||||
|
||||
pub(super) async fn recheck(
|
||||
conn: &mut PgConnection,
|
||||
scope: &Scope,
|
||||
remaining: &[String],
|
||||
) -> Result<()> {
|
||||
// Lock original identities too, so transfers away cannot race validation.
|
||||
sqlx::query("SELECT pubkey FROM users WHERE community_id=$1 AND pubkey=ANY($2::bytea[]) ORDER BY pubkey FOR SHARE")
|
||||
.bind(scope.community).bind(&scope.bytes).fetch_all(&mut *conn).await?;
|
||||
if targets(conn, scope.community, &scope.human, true).await? != remaining {
|
||||
return Err(invalid(
|
||||
"community agent ownership changed; retry to discover current agents",
|
||||
));
|
||||
}
|
||||
plan::validate_ownership(conn, scope).await
|
||||
}
|
||||
124
crates/buzz-db/src/store/user_deletion/profile_batches/plan.rs
Normal file
124
crates/buzz-db/src/store/user_deletion/profile_batches/plan.rs
Normal file
@@ -0,0 +1,124 @@
|
||||
use super::*;
|
||||
use sqlx::Row;
|
||||
|
||||
pub(super) async fn build(conn: &mut PgConnection, options: &ProfileBatchOptions) -> Result<Plan> {
|
||||
let human = normalize_user_deletion_pubkey(&options.pubkey)?;
|
||||
let targets = ownership::targets(conn, options.community, &human, false).await?;
|
||||
let relays: Vec<String> = options
|
||||
.relay_pubkeys
|
||||
.iter()
|
||||
.map(|p| normalize_user_deletion_pubkey(p))
|
||||
.collect::<Result<_>>()?;
|
||||
if relays.iter().any(|p| targets.contains(p)) {
|
||||
return Err(invalid("target keys and trusted relay keys must differ"));
|
||||
}
|
||||
let bytes = targets
|
||||
.iter()
|
||||
.map(|p| hex::decode(p).map_err(|_| invalid("invalid target key")))
|
||||
.collect::<Result<_>>()?;
|
||||
let scope = Scope {
|
||||
community: options.community,
|
||||
human,
|
||||
targets,
|
||||
bytes,
|
||||
relays,
|
||||
};
|
||||
let active: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM communities WHERE id=$1 AND deletion_state='active' AND deleted_at IS NULL)")
|
||||
.bind(scope.community).fetch_one(&mut *conn).await?;
|
||||
if !active {
|
||||
return Err(invalid(
|
||||
"community is absent or undergoing whole-community deletion",
|
||||
));
|
||||
}
|
||||
validate_ownership(conn, &scope).await?;
|
||||
inspect(conn, scope, options.max_items).await
|
||||
}
|
||||
|
||||
// Only callers with a scope freshly discovered by this invocation may inspect it.
|
||||
// This never executes mutations; final inspection may include identities we removed.
|
||||
pub(super) async fn inspect(conn: &mut PgConnection, scope: Scope, max_items: u32) -> Result<Plan> {
|
||||
let blockers = dependencies(conn, &scope).await?;
|
||||
let mut plan = Plan {
|
||||
scope,
|
||||
ops: Vec::new(),
|
||||
blockers,
|
||||
};
|
||||
let selected = events::select(conn, &plan.scope, max_items).await?;
|
||||
let ids: Vec<Vec<u8>> = selected.iter().map(|e| e.id.clone()).collect();
|
||||
// Threaded/channel-bearing data belongs to content cleanup; never break a surviving discussion.
|
||||
let threaded: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM thread_metadata WHERE community_id=$1 AND (event_id=ANY($2::bytea[]) OR parent_event_id=ANY($2::bytea[]) OR root_event_id=ANY($2::bytea[])))")
|
||||
.bind(plan.scope.community).bind(&ids).fetch_one(&mut *conn).await?;
|
||||
if threaded {
|
||||
plan.blockers
|
||||
.push("selected profiles have thread dependencies; content cleanup required".into());
|
||||
}
|
||||
for table in rows::CHILDREN {
|
||||
rows::collect(conn, &mut plan, table, &ids, max_items).await?;
|
||||
}
|
||||
let mut snapshots = Vec::new();
|
||||
for event in selected {
|
||||
let op = rows::Operation {
|
||||
table: &rows::EVENTS,
|
||||
key: event.key,
|
||||
fingerprint: event.fingerprint,
|
||||
snapshot: event.snapshot,
|
||||
};
|
||||
if op.snapshot.is_some() {
|
||||
snapshots.push(op);
|
||||
} else {
|
||||
rows::push(&mut plan, op, max_items)?;
|
||||
}
|
||||
}
|
||||
rows::collect(conn, &mut plan, &rows::HEADS, &[], max_items).await?;
|
||||
rows::collect(conn, &mut plan, &rows::ARCHIVES, &[], max_items).await?;
|
||||
// Archive rows go first, then snapshots; retries can find stale snapshots while identities remain.
|
||||
for op in snapshots {
|
||||
rows::push(&mut plan, op, max_items)?;
|
||||
}
|
||||
let before_users = plan.ops.len();
|
||||
rows::collect(conn, &mut plan, &rows::USERS, &[], max_items).await?;
|
||||
let human_bytea = format!("\\x{}", plan.scope.human);
|
||||
plan.ops[before_users..].sort_by_key(|op| op.key["pubkey"].as_str() == Some(&human_bytea));
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
pub(super) async fn validate_ownership(conn: &mut PgConnection, scope: &Scope) -> Result<()> {
|
||||
let conflict: bool=sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM users WHERE community_id=$1 AND \
|
||||
((pubkey=ANY($2::bytea[]) AND pubkey<>decode($3,'hex') AND agent_owner_pubkey IS DISTINCT FROM decode($3,'hex')) \
|
||||
OR (agent_owner_pubkey=ANY($2::bytea[]) AND NOT(pubkey=ANY($2::bytea[])))))")
|
||||
.bind(scope.community).bind(&scope.bytes).bind(&scope.human).fetch_one(conn).await?;
|
||||
if conflict {
|
||||
return Err(invalid(
|
||||
"agent ownership changed, is missing, or has unselected dependents",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn dependencies(conn: &mut PgConnection, scope: &Scope) -> Result<Vec<String>> {
|
||||
let mut blockers = Vec::new();
|
||||
// Static fragments only. These checks also run immediately before final user removal.
|
||||
// Repository announcements/state (30617/30618) survive content and profile cleanup.
|
||||
// Keep this exemption narrow: other authored content still requires disposition.
|
||||
for (table, selector) in [
|
||||
("api_tokens","owner_pubkey=ANY($2::bytea[])"),
|
||||
("workflows","owner_pubkey=ANY($2::bytea[])"),
|
||||
("subscriptions","owner_pubkey=ANY($2::bytea[])"),
|
||||
("channel_members","pubkey=ANY($2::bytea[])"),
|
||||
("relay_members","pubkey=ANY(SELECT encode(k,'hex') FROM unnest($2::bytea[]) k)"),
|
||||
("events","pubkey=ANY($2::bytea[]) AND kind NOT IN (0,10100,30177,30179,9035,9036,30617,30618)"),
|
||||
("archived_identities","NOT(pubkey=ANY(SELECT encode(k,'hex') FROM unnest($2::bytea[]) k)) AND (actor=ANY(SELECT encode(k,'hex') FROM unnest($2::bytea[]) k) OR replaced_by=ANY(SELECT encode(k,'hex') FROM unnest($2::bytea[]) k))"),
|
||||
] {
|
||||
let sql=format!("SELECT EXISTS(SELECT 1 FROM {table} WHERE community_id=$1 AND ({selector}))");
|
||||
let exists:bool=sqlx::query_scalar(sqlx::AssertSqlSafe(sql)).bind(scope.community).bind(&scope.bytes).fetch_one(&mut *conn).await?;
|
||||
if exists {blockers.push(format!("{table}: content/account cleanup or shared-reference disposition required"));}
|
||||
}
|
||||
// Avoid silently erasing an ownership link through the users self-FK.
|
||||
let rows=sqlx::query("SELECT encode(pubkey,'hex') AS pubkey FROM users WHERE community_id=$1 AND agent_owner_pubkey=ANY($2::bytea[]) AND NOT(pubkey=ANY($2::bytea[])) LIMIT 1")
|
||||
.bind(scope.community).bind(&scope.bytes).fetch_all(conn).await?;
|
||||
if let Some(row) = rows.first() {
|
||||
let _: String = row.try_get("pubkey")?;
|
||||
blockers.push("unselected agent depends on a target identity".into());
|
||||
}
|
||||
Ok(blockers)
|
||||
}
|
||||
@@ -0,0 +1,906 @@
|
||||
use super::*;
|
||||
use nostr::{Event, EventBuilder, Keys, Kind, Tag, Timestamp};
|
||||
use sqlx::PgPool;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
struct Fixture {
|
||||
pool: PgPool,
|
||||
store: UserDeletionStore,
|
||||
community: Uuid,
|
||||
elsewhere: Uuid,
|
||||
human: Keys,
|
||||
agent: Keys,
|
||||
other: Keys,
|
||||
relay: Keys,
|
||||
}
|
||||
impl Fixture {
|
||||
async fn new() -> Self {
|
||||
let pool = PgPool::connect(&crate::test_support::database_url())
|
||||
.await
|
||||
.unwrap();
|
||||
let store = crate::Db::from_pool(pool.clone()).user_deletion_store();
|
||||
let f = Self {
|
||||
pool,
|
||||
store,
|
||||
community: Uuid::new_v4(),
|
||||
elsewhere: Uuid::new_v4(),
|
||||
human: Keys::generate(),
|
||||
agent: Keys::generate(),
|
||||
other: Keys::generate(),
|
||||
relay: Keys::generate(),
|
||||
};
|
||||
for c in [f.community, f.elsewhere] {
|
||||
sqlx::query("INSERT INTO communities(id,host) VALUES($1,$2)")
|
||||
.bind(c)
|
||||
.bind(format!("{c}.example.org"))
|
||||
.execute(&f.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
for k in [&f.human, &f.agent, &f.other] {
|
||||
sqlx::query("INSERT INTO users(community_id,pubkey,display_name) VALUES($1,$2,'profile fixture')").bind(c).bind(k.public_key().to_bytes().as_slice()).execute(&f.pool).await.unwrap();
|
||||
}
|
||||
sqlx::query(
|
||||
"UPDATE users SET agent_owner_pubkey=$2 WHERE community_id=$1 AND pubkey=$3",
|
||||
)
|
||||
.bind(c)
|
||||
.bind(f.human.public_key().to_bytes().as_slice())
|
||||
.bind(f.agent.public_key().to_bytes().as_slice())
|
||||
.execute(&f.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
f
|
||||
}
|
||||
fn options(&self, batch_size: u16) -> ProfileBatchOptions {
|
||||
ProfileBatchOptions {
|
||||
community: self.community,
|
||||
pubkey: self.human.public_key().to_hex(),
|
||||
relay_pubkeys: vec![self.relay.public_key().to_hex()],
|
||||
batch_size,
|
||||
max_items: 1000,
|
||||
}
|
||||
}
|
||||
async fn event(
|
||||
&self,
|
||||
c: Uuid,
|
||||
key: &Keys,
|
||||
kind: u16,
|
||||
tags: Vec<Vec<String>>,
|
||||
content: &str,
|
||||
) -> Event {
|
||||
// Self-archive requests must retain the author as their explicit p subject.
|
||||
let event = EventBuilder::new(Kind::Custom(kind), content)
|
||||
.allow_self_tagging()
|
||||
.tags(tags.into_iter().map(|v| Tag::parse(v).unwrap()))
|
||||
.custom_created_at(Timestamp::now())
|
||||
.sign_with_keys(key)
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO events(community_id,id,pubkey,created_at,kind,tags,content,sig) VALUES($1,$2,$3,$4,$5,$6,$7,$8)")
|
||||
.bind(c).bind(event.id.to_bytes().as_slice()).bind(event.pubkey.to_bytes().as_slice())
|
||||
.bind(chrono::DateTime::from_timestamp(event.created_at.as_secs() as i64,0).unwrap())
|
||||
.bind(i32::from(kind)).bind(serde_json::to_value(&event.tags).unwrap()).bind(&event.content).bind(event.sig.serialize().as_slice())
|
||||
.execute(&self.pool).await.unwrap();
|
||||
event
|
||||
}
|
||||
async fn profiles(&self) {
|
||||
for c in [self.community, self.elsewhere] {
|
||||
self.event(c, &self.human, 0, vec![], "human profile").await;
|
||||
self.event(c, &self.agent, 10100, vec![], "agent profile")
|
||||
.await;
|
||||
self.event(c, &self.other, 0, vec![], "surviving profile")
|
||||
.await;
|
||||
self.event(
|
||||
c,
|
||||
&self.human,
|
||||
30177,
|
||||
vec![vec!["d".into(), self.agent.public_key().to_hex()]],
|
||||
"configuration",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let subject = self.human.public_key().to_hex();
|
||||
let event = self
|
||||
.event(
|
||||
self.community,
|
||||
&self.relay,
|
||||
30382,
|
||||
vec![
|
||||
vec!["d".into(), subject.clone()],
|
||||
vec!["p".into(), subject.clone()],
|
||||
],
|
||||
"",
|
||||
)
|
||||
.await;
|
||||
sqlx::query("INSERT INTO nip_fi_profile_heads(community_id,pubkey,issuer,issued_at,event) VALUES($1,$2,'https://issuer.example.org',1,$3)")
|
||||
.bind(self.community).bind(&subject).bind(serde_json::to_value(&event).unwrap()).execute(&self.pool).await.unwrap();
|
||||
sqlx::query("INSERT INTO event_mentions(community_id,pubkey_hex,event_id,event_created_at,event_kind) VALUES($1,$2,$3,now(),30382)")
|
||||
.bind(self.community).bind(&subject).bind(event.id.to_bytes().as_slice()).execute(&self.pool).await.unwrap();
|
||||
for key in [&self.human, &self.other] {
|
||||
sqlx::query("INSERT INTO archived_identities(community_id,pubkey,consent_path,actor,request_event_id) VALUES($1,$2,'self',$2,$3)")
|
||||
.bind(self.community).bind(key.public_key().to_hex()).bind("a".repeat(64)).execute(&self.pool).await.unwrap();
|
||||
}
|
||||
self.event(
|
||||
self.community,
|
||||
&self.relay,
|
||||
13535,
|
||||
vec![
|
||||
vec!["-".into()],
|
||||
vec!["p".into(), subject],
|
||||
vec!["p".into(), self.other.public_key().to_hex()],
|
||||
],
|
||||
"",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn export(pool: &PgPool) -> BTreeMap<String, Value> {
|
||||
let tables: Vec<String> = sqlx::query_scalar(
|
||||
"SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut result = BTreeMap::new();
|
||||
for table in tables {
|
||||
let sql=format!("SELECT COALESCE(jsonb_agg(to_jsonb(t) ORDER BY to_jsonb(t)::text),'[]'::jsonb) FROM public.\"{}\" t",table.replace('"',"\"\""));
|
||||
result.insert(
|
||||
table,
|
||||
sqlx::query_scalar(sqlx::AssertSqlSafe(sql))
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires Postgres"]
|
||||
async fn preview_delete_retry_preserve_other_identities_and_communities() {
|
||||
let f = Fixture::new().await;
|
||||
f.profiles().await;
|
||||
let before = export(&f.pool).await;
|
||||
let mut preview = Vec::new();
|
||||
let opts = f.options(2);
|
||||
let expected = f
|
||||
.store
|
||||
.run_profile_batches(&opts, false, None, &mut preview)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(before, export(&f.pool).await, "preview changed database");
|
||||
assert!(expected.items > 2);
|
||||
assert!(expected.batches > 1);
|
||||
let output = String::from_utf8(preview).unwrap();
|
||||
assert!(output.contains("replace_archive_snapshot"));
|
||||
assert!(!output.contains("configuration"));
|
||||
assert!(!output.contains("human profile"));
|
||||
let mut deletion = Vec::new();
|
||||
let actual = f
|
||||
.store
|
||||
.run_profile_batches(
|
||||
&opts,
|
||||
true,
|
||||
Some(&f.relay.secret_key().to_secret_hex()),
|
||||
&mut deletion,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(actual.items, expected.items);
|
||||
let after = export(&f.pool).await;
|
||||
for (table, rows) in &before {
|
||||
if ![
|
||||
"events",
|
||||
"users",
|
||||
"nip_fi_profile_heads",
|
||||
"archived_identities",
|
||||
"event_mentions",
|
||||
]
|
||||
.contains(&table.as_str())
|
||||
&& !table.starts_with("events_")
|
||||
{
|
||||
assert_eq!(rows, &after[table], "unexpected change to {table}");
|
||||
}
|
||||
}
|
||||
let remaining: Vec<Vec<u8>> =
|
||||
sqlx::query_scalar("SELECT pubkey FROM users WHERE community_id=$1")
|
||||
.bind(f.community)
|
||||
.fetch_all(&f.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(remaining, vec![f.other.public_key().to_bytes().to_vec()]);
|
||||
for (table, old_rows) in &before {
|
||||
for row in old_rows.as_array().unwrap() {
|
||||
let key = row["pubkey"]
|
||||
.as_str()
|
||||
.unwrap_or("")
|
||||
.trim_start_matches("\\x");
|
||||
if row["community_id"] == json!(f.elsewhere) || key == f.other.public_key().to_hex() {
|
||||
assert!(
|
||||
after[table].as_array().unwrap().contains(row),
|
||||
"survivor changed in {table}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
let other_count: i64 = sqlx::query_scalar("SELECT count(*) FROM users WHERE community_id=$1")
|
||||
.bind(f.elsewhere)
|
||||
.fetch_one(&f.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(other_count, 3);
|
||||
let snapshot=sqlx::query("SELECT id,pubkey,extract(epoch FROM created_at)::bigint AS created_at,kind,tags,content,sig FROM events WHERE community_id=$1 AND kind=13535").bind(f.community).fetch_one(&f.pool).await.unwrap();
|
||||
use sqlx::Row;
|
||||
let signed:Event=serde_json::from_value(json!({"id":hex::encode(snapshot.get::<Vec<u8>,_>("id")),"pubkey":hex::encode(snapshot.get::<Vec<u8>,_>("pubkey")),"created_at":snapshot.get::<i64,_>("created_at"),"kind":13535,"tags":snapshot.get::<Value,_>("tags"),"content":snapshot.get::<String,_>("content"),"sig":hex::encode(snapshot.get::<Vec<u8>,_>("sig"))})).unwrap();
|
||||
signed.verify().unwrap();
|
||||
assert_eq!(
|
||||
signed
|
||||
.tags
|
||||
.iter()
|
||||
.filter(|t| t.as_slice().first().map(String::as_str) == Some("p"))
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert!(serde_json::to_string(&signed.tags)
|
||||
.unwrap()
|
||||
.contains(&f.other.public_key().to_hex()));
|
||||
assert!(!serde_json::to_string(&signed.tags)
|
||||
.unwrap()
|
||||
.contains(&f.human.public_key().to_hex()));
|
||||
let second = f
|
||||
.store
|
||||
.run_profile_batches(&opts, true, None, &mut Vec::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(second.items, 0);
|
||||
assert_eq!(after, export(&f.pool).await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires Postgres"]
|
||||
async fn limits_dependencies_and_signer_fail_before_any_mutation() {
|
||||
let f = Fixture::new().await;
|
||||
f.profiles().await;
|
||||
let before = export(&f.pool).await;
|
||||
let mut opts = f.options(1);
|
||||
opts.max_items = 1;
|
||||
assert!(f
|
||||
.store
|
||||
.run_profile_batches(&opts, true, None, &mut Vec::new())
|
||||
.await
|
||||
.is_err());
|
||||
opts.max_items = 1000;
|
||||
for key in [None, Some(f.other.secret_key().to_secret_hex())] {
|
||||
assert!(f
|
||||
.store
|
||||
.run_profile_batches(&opts, true, key.as_deref(), &mut Vec::new())
|
||||
.await
|
||||
.is_err());
|
||||
assert_eq!(before, export(&f.pool).await);
|
||||
}
|
||||
opts.relay_pubkeys.clear();
|
||||
assert!(f
|
||||
.store
|
||||
.run_profile_batches(&opts, false, None, &mut Vec::new())
|
||||
.await
|
||||
.is_err());
|
||||
assert_eq!(before, export(&f.pool).await);
|
||||
opts = f.options(1);
|
||||
f.event(
|
||||
f.community,
|
||||
&f.agent,
|
||||
1,
|
||||
vec![],
|
||||
"content must be cleaned first",
|
||||
)
|
||||
.await;
|
||||
let before = export(&f.pool).await;
|
||||
let mut output = Vec::new();
|
||||
assert!(f
|
||||
.store
|
||||
.run_profile_batches(
|
||||
&opts,
|
||||
true,
|
||||
Some(&f.relay.secret_key().to_secret_hex()),
|
||||
&mut output
|
||||
)
|
||||
.await
|
||||
.is_err());
|
||||
assert!(String::from_utf8(output)
|
||||
.unwrap()
|
||||
.contains("content/account cleanup"));
|
||||
assert_eq!(before, export(&f.pool).await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires Postgres"]
|
||||
async fn content_then_profile_cleanup_retains_human_and_agent_repositories() {
|
||||
use crate::user_deletion::{content_batches::ContentBatchOptions, ExecutionMode};
|
||||
|
||||
let f = Fixture::new().await;
|
||||
f.profiles().await;
|
||||
let mut repository_ids = Vec::new();
|
||||
for community in [f.community, f.elsewhere] {
|
||||
for owner in [&f.human, &f.agent, &f.other] {
|
||||
let repo = format!("repo-{}", owner.public_key());
|
||||
for kind in [30617, 30618] {
|
||||
let event = f
|
||||
.event(
|
||||
community,
|
||||
owner,
|
||||
kind,
|
||||
vec![vec!["d".into(), repo.clone()]],
|
||||
"retained repository metadata",
|
||||
)
|
||||
.await;
|
||||
repository_ids.push(json!(format!("\\x{}", event.id)));
|
||||
sqlx::query("INSERT INTO event_mentions(community_id,pubkey_hex,event_id,event_created_at,event_kind) VALUES($1,$2,$3,now(),$4)")
|
||||
.bind(community).bind(f.other.public_key().to_hex())
|
||||
.bind(event.id.to_bytes().as_slice()).bind(i32::from(kind))
|
||||
.execute(&f.pool).await.unwrap();
|
||||
}
|
||||
sqlx::query(
|
||||
"INSERT INTO git_repo_names(community_id,repo_id,owner_pubkey) VALUES($1,$2,$3)",
|
||||
)
|
||||
.bind(community)
|
||||
.bind(repo)
|
||||
.bind(owner.public_key().to_hex())
|
||||
.execute(&f.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
// Retaining repositories must not exempt ordinary human or agent content.
|
||||
for owner in [&f.human, &f.agent] {
|
||||
f.event(f.community, owner, 1, vec![], "remove content first")
|
||||
.await;
|
||||
}
|
||||
let before = export(&f.pool).await;
|
||||
let opts = f.options(2);
|
||||
let secret = f.relay.secret_key().to_secret_hex();
|
||||
let mut blocked = Vec::new();
|
||||
assert!(f
|
||||
.store
|
||||
.run_profile_batches(&opts, true, Some(&secret), &mut blocked)
|
||||
.await
|
||||
.is_err());
|
||||
assert!(String::from_utf8(blocked)
|
||||
.unwrap()
|
||||
.contains("events: content/account cleanup"));
|
||||
assert_eq!(before, export(&f.pool).await);
|
||||
f.store
|
||||
.run_message_batches(
|
||||
&ContentBatchOptions {
|
||||
community: f.community,
|
||||
pubkey: f.human.public_key().to_hex(),
|
||||
relay_pubkey: Some(f.relay.public_key().to_hex()),
|
||||
batch_size: 2,
|
||||
max_items: 1000,
|
||||
},
|
||||
ExecutionMode::Delete,
|
||||
None,
|
||||
&mut Vec::new(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let after_content = export(&f.pool).await;
|
||||
let mut preview = Vec::new();
|
||||
let proposed = f
|
||||
.store
|
||||
.run_profile_batches(&opts, false, None, &mut preview)
|
||||
.await
|
||||
.unwrap();
|
||||
let start: Value =
|
||||
serde_json::from_slice(preview.split(|b| *b == b'\n').next().unwrap()).unwrap();
|
||||
assert_eq!(start["blockers"], json!([]));
|
||||
assert_eq!(after_content, export(&f.pool).await);
|
||||
let deleted = f
|
||||
.store
|
||||
.run_profile_batches(&opts, true, Some(&secret), &mut Vec::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(proposed.items, deleted.items);
|
||||
let after = export(&f.pool).await;
|
||||
assert_eq!(before["git_repo_names"], after["git_repo_names"]);
|
||||
for (table, rows) in &before {
|
||||
for row in rows.as_array().unwrap() {
|
||||
if row["community_id"] == json!(f.elsewhere)
|
||||
|| (table == "events" && repository_ids.contains(&row["id"]))
|
||||
|| (table == "event_mentions" && repository_ids.contains(&row["event_id"]))
|
||||
{
|
||||
assert!(
|
||||
after[table].as_array().unwrap().contains(row),
|
||||
"retained row changed in {table}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
let remaining: Vec<Vec<u8>> =
|
||||
sqlx::query_scalar("SELECT pubkey FROM users WHERE community_id=$1")
|
||||
.bind(f.community)
|
||||
.fetch_all(&f.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(remaining, vec![f.other.public_key().to_bytes().to_vec()]);
|
||||
assert_eq!(
|
||||
f.store
|
||||
.run_profile_batches(&opts, true, None, &mut Vec::new())
|
||||
.await
|
||||
.unwrap()
|
||||
.items,
|
||||
0
|
||||
);
|
||||
assert_eq!(after, export(&f.pool).await);
|
||||
}
|
||||
|
||||
struct FailAfterCommit;
|
||||
impl Write for FailAfterCommit {
|
||||
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||
if String::from_utf8_lossy(bytes).contains("batch_committed") {
|
||||
Err(std::io::Error::other("injected output loss"))
|
||||
} else {
|
||||
Ok(bytes.len())
|
||||
}
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
#[ignore = "requires Postgres"]
|
||||
async fn commit_before_output_loss_resumes_from_same_target_scope() {
|
||||
let f = Fixture::new().await;
|
||||
f.profiles().await;
|
||||
let opts = f.options(2);
|
||||
assert!(f
|
||||
.store
|
||||
.run_profile_batches(
|
||||
&opts,
|
||||
true,
|
||||
Some(&f.relay.secret_key().to_secret_hex()),
|
||||
&mut FailAfterCommit
|
||||
)
|
||||
.await
|
||||
.is_err());
|
||||
let mut output = Vec::new();
|
||||
f.store
|
||||
.run_profile_batches(
|
||||
&opts,
|
||||
true,
|
||||
Some(&f.relay.secret_key().to_secret_hex()),
|
||||
&mut output,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(String::from_utf8(output)
|
||||
.unwrap()
|
||||
.contains("delete_complete"));
|
||||
assert_eq!(
|
||||
f.store
|
||||
.run_profile_batches(&opts, true, None, &mut Vec::new())
|
||||
.await
|
||||
.unwrap()
|
||||
.items,
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires Postgres"]
|
||||
async fn changed_source_rolls_back_batch_and_changed_owner_is_refused() {
|
||||
let f = Fixture::new().await;
|
||||
f.event(f.community, &f.human, 0, vec![], "initial").await;
|
||||
let mut conn = f.pool.acquire().await.unwrap();
|
||||
let plan = plan::build(&mut conn, &f.options(100)).await.unwrap();
|
||||
sqlx::query("UPDATE events SET content='changed' WHERE community_id=$1")
|
||||
.bind(f.community)
|
||||
.execute(&f.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut raw = f.pool.begin().await.unwrap();
|
||||
lock(&mut raw, &plan.scope).await.unwrap();
|
||||
let mut tx = crate::AdmittedTx::admit(
|
||||
raw,
|
||||
&crate::deletion::DeletionStore::new(f.pool.clone()),
|
||||
buzz_core::CommunityId::from_uuid(f.community),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
rows::apply(&mut tx, &plan.scope, &plan.ops[0], &Default::default())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
tx.rollback().await.unwrap();
|
||||
let before = export(&f.pool).await;
|
||||
sqlx::query("UPDATE users SET agent_owner_pubkey=$2 WHERE community_id=$1 AND pubkey=$3")
|
||||
.bind(f.community)
|
||||
.bind(f.other.public_key().to_bytes().as_slice())
|
||||
.bind(f.agent.public_key().to_bytes().as_slice())
|
||||
.execute(&f.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut tx = f.pool.begin().await.unwrap();
|
||||
assert!(
|
||||
ownership::recheck(&mut tx, &plan.scope, &plan.scope.targets)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
tx.rollback().await.unwrap();
|
||||
assert_eq!(before["events"], export(&f.pool).await["events"]);
|
||||
// A new invocation excludes the transferred agent instead of trusting the old plan.
|
||||
let result = f
|
||||
.store
|
||||
.run_profile_batches(&f.options(100), true, None, &mut Vec::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result.target_pubkeys, vec![f.human.public_key().to_hex()]);
|
||||
let owner: Vec<u8> = sqlx::query_scalar(
|
||||
"SELECT agent_owner_pubkey FROM users WHERE community_id=$1 AND pubkey=$2",
|
||||
)
|
||||
.bind(f.community)
|
||||
.bind(f.agent.public_key().to_bytes().as_slice())
|
||||
.fetch_one(&f.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(owner, f.other.public_key().to_bytes());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires Postgres"]
|
||||
async fn mismatched_verified_subject_and_survivor_archive_actor_are_not_erased() {
|
||||
let f = Fixture::new().await;
|
||||
f.event(
|
||||
f.community,
|
||||
&f.relay,
|
||||
30382,
|
||||
vec![
|
||||
vec!["p".into(), f.human.public_key().to_hex()],
|
||||
vec!["d".into(), f.other.public_key().to_hex()],
|
||||
],
|
||||
"",
|
||||
)
|
||||
.await;
|
||||
let before = export(&f.pool).await;
|
||||
assert!(f
|
||||
.store
|
||||
.run_profile_batches(&f.options(100), true, None, &mut Vec::new())
|
||||
.await
|
||||
.is_err());
|
||||
assert_eq!(before, export(&f.pool).await);
|
||||
}
|
||||
|
||||
// Hooks run at the public handler's output boundary, exercising the real batch path.
|
||||
struct RecordHook<F>(F);
|
||||
impl<F: FnMut(Value) -> std::io::Result<()>> Write for RecordHook<F> {
|
||||
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||
if let Ok(record) = serde_json::from_slice(bytes) {
|
||||
(self.0)(record)?;
|
||||
}
|
||||
Ok(bytes.len())
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires Postgres"]
|
||||
async fn community_ownership_and_retry_after_identity_removal() {
|
||||
// Ownership elsewhere is neither conflicting local ownership nor missing local evidence.
|
||||
for missing in [false, true] {
|
||||
let f = Fixture::new().await;
|
||||
f.event(f.community, &f.human, 0, vec![], "human").await;
|
||||
f.event(f.community, &f.agent, 10100, vec![], "retain agent")
|
||||
.await;
|
||||
if missing {
|
||||
sqlx::query("DELETE FROM users WHERE community_id=$1 AND pubkey=$2")
|
||||
.bind(f.community)
|
||||
.bind(f.agent.public_key().to_bytes().as_slice())
|
||||
.execute(&f.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
} else {
|
||||
sqlx::query(
|
||||
"UPDATE users SET agent_owner_pubkey=$3 WHERE community_id=$1 AND pubkey=$2",
|
||||
)
|
||||
.bind(f.community)
|
||||
.bind(f.agent.public_key().to_bytes().as_slice())
|
||||
.bind(f.other.public_key().to_bytes().as_slice())
|
||||
.execute(&f.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let before = export(&f.pool).await;
|
||||
let preview = f
|
||||
.store
|
||||
.run_profile_batches(&f.options(1), false, None, &mut Vec::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(preview.target_pubkeys, vec![f.human.public_key().to_hex()]);
|
||||
assert_eq!(before, export(&f.pool).await);
|
||||
f.store
|
||||
.run_profile_batches(&f.options(1), true, None, &mut Vec::new())
|
||||
.await
|
||||
.unwrap();
|
||||
let after = export(&f.pool).await;
|
||||
for (table, rows) in &before {
|
||||
for row in rows.as_array().unwrap() {
|
||||
if row["community_id"] == json!(f.elsewhere)
|
||||
|| row["pubkey"] == format!("\\x{}", f.agent.public_key())
|
||||
{
|
||||
assert!(
|
||||
after[table].as_array().unwrap().contains(row),
|
||||
"survivor changed in {table}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let f = Fixture::new().await;
|
||||
f.event(f.community, &f.human, 0, vec![], "human").await;
|
||||
f.event(f.community, &f.agent, 10100, vec![], "agent").await;
|
||||
let mut removing_agent = false;
|
||||
let mut output = RecordHook(|record: Value| {
|
||||
if record["record"] == "proposed_batch" {
|
||||
removing_agent = record["items"][0]["table"] == "users"
|
||||
&& record["items"][0]["key"]["pubkey"] == format!("\\x{}", f.agent.public_key());
|
||||
}
|
||||
if record["record"] == "batch_committed" && removing_agent {
|
||||
return Err(std::io::Error::other(
|
||||
"lost output after agent identity commit",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
assert!(f
|
||||
.store
|
||||
.run_profile_batches(&f.options(1), true, None, &mut output)
|
||||
.await
|
||||
.is_err());
|
||||
let remaining: Vec<Vec<u8>> =
|
||||
sqlx::query_scalar("SELECT pubkey FROM users WHERE community_id=$1")
|
||||
.bind(f.community)
|
||||
.fetch_all(&f.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!remaining.contains(&f.agent.public_key().to_bytes().to_vec()));
|
||||
assert!(remaining.contains(&f.human.public_key().to_bytes().to_vec()));
|
||||
let agent_events: i64 =
|
||||
sqlx::query_scalar("SELECT count(*) FROM events WHERE community_id=$1 AND pubkey=$2")
|
||||
.bind(f.community)
|
||||
.bind(f.agent.public_key().to_bytes().as_slice())
|
||||
.fetch_one(&f.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
agent_events, 0,
|
||||
"identity removal stranded undiscoverable profile data"
|
||||
);
|
||||
|
||||
let retry = f
|
||||
.store
|
||||
.run_profile_batches(&f.options(1), true, None, &mut Vec::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(retry.target_pubkeys, vec![f.human.public_key().to_hex()]);
|
||||
assert_eq!(retry.items, 1);
|
||||
assert_eq!(
|
||||
f.store
|
||||
.run_profile_batches(&f.options(1), true, None, &mut Vec::new())
|
||||
.await
|
||||
.unwrap()
|
||||
.items,
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "requires Postgres"]
|
||||
async fn ownership_changes_before_write_are_refused_and_retry_rediscovers() {
|
||||
for change in ["transfer", "missing", "new"] {
|
||||
let f = Fixture::new().await;
|
||||
f.event(f.community, &f.human, 0, vec![], "human").await;
|
||||
f.event(f.community, &f.agent, 10100, vec![], "agent").await;
|
||||
let mut changed = false;
|
||||
let mut output = RecordHook(|record: Value| {
|
||||
if record["record"] == "proposed_batch" && !changed {
|
||||
changed = true;
|
||||
tokio::task::block_in_place(|| {
|
||||
tokio::runtime::Handle::current().block_on(async {
|
||||
let sql = match change {
|
||||
"transfer" => "UPDATE users SET agent_owner_pubkey=$3 WHERE community_id=$1 AND pubkey=$2",
|
||||
"missing" => "UPDATE users SET agent_owner_pubkey=NULL WHERE community_id=$1 AND pubkey=$2 AND $3::bytea IS NOT NULL",
|
||||
_ => "UPDATE users SET agent_owner_pubkey=$2 WHERE community_id=$1 AND pubkey=$3",
|
||||
};
|
||||
let key = if change == "new" { &f.human } else { &f.agent };
|
||||
sqlx::query(sql).bind(f.community).bind(key.public_key().to_bytes().as_slice())
|
||||
.bind(f.other.public_key().to_bytes().as_slice()).execute(&f.pool).await.unwrap();
|
||||
})
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
let before = export(&f.pool).await;
|
||||
let error = f
|
||||
.store
|
||||
.run_profile_batches(&f.options(1), true, None, &mut output)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("ownership changed"), "{error}");
|
||||
assert!(changed);
|
||||
assert_eq!(before["events"], export(&f.pool).await["events"]);
|
||||
let retry = f
|
||||
.store
|
||||
.run_profile_batches(&f.options(1), true, None, &mut Vec::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
retry.target_pubkeys.len(),
|
||||
if change == "new" { 3 } else { 1 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "requires Postgres"]
|
||||
async fn final_check_keeps_removed_agent_scope_and_locks_ownership() {
|
||||
let f = Fixture::new().await;
|
||||
f.event(f.community, &f.agent, 10100, vec![], "initial")
|
||||
.await;
|
||||
let mut conn = f.pool.acquire().await.unwrap();
|
||||
let plan = plan::build(&mut conn, &f.options(1)).await.unwrap();
|
||||
let mut checked = f.pool.begin().await.unwrap();
|
||||
ownership::recheck(&mut checked, &plan.scope, &plan.scope.targets)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut transfer = f.pool.begin().await.unwrap();
|
||||
sqlx::query("SET LOCAL lock_timeout='100ms'")
|
||||
.execute(&mut *transfer)
|
||||
.await
|
||||
.unwrap();
|
||||
let error =
|
||||
sqlx::query("UPDATE users SET agent_owner_pubkey=$3 WHERE community_id=$1 AND pubkey=$2")
|
||||
.bind(f.community)
|
||||
.bind(f.agent.public_key().to_bytes().as_slice())
|
||||
.bind(f.other.public_key().to_bytes().as_slice())
|
||||
.execute(&mut *transfer)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
error.as_database_error().unwrap().code().as_deref(),
|
||||
Some("55P03")
|
||||
);
|
||||
transfer.rollback().await.unwrap();
|
||||
checked.rollback().await.unwrap();
|
||||
drop(conn);
|
||||
|
||||
let mut removing_human = false;
|
||||
let mut inserted = false;
|
||||
let mut output = RecordHook(|record: Value| {
|
||||
if record["record"] == "proposed_batch" {
|
||||
removing_human = record["items"][0]["table"] == "users"
|
||||
&& record["items"][0]["key"]["pubkey"] == format!("\\x{}", f.human.public_key());
|
||||
}
|
||||
if record["record"] == "batch_committed" && removing_human {
|
||||
// Simulate an out-of-contract writer: final verification must still see
|
||||
// the erased agent's residual data after ownership discovery shrinks.
|
||||
tokio::task::block_in_place(|| {
|
||||
tokio::runtime::Handle::current().block_on(f.event(
|
||||
f.community,
|
||||
&f.agent,
|
||||
10100,
|
||||
vec![],
|
||||
"late residual profile",
|
||||
))
|
||||
});
|
||||
inserted = true;
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
let error = f
|
||||
.store
|
||||
.run_profile_batches(&f.options(1), true, None, &mut output)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(inserted);
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("profile rows or dependencies remain"),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
|
||||
async fn historical_replacement_blocks_cleanup_after_unarchive(kind: u16) {
|
||||
for agent in [false, true] {
|
||||
let f = Fixture::new().await;
|
||||
let replacement = if agent { &f.agent } else { &f.human };
|
||||
let subject = f.other.public_key().to_hex();
|
||||
let replacement = replacement.public_key().to_hex();
|
||||
let signer = if kind == 9035 { &f.other } else { &f.relay };
|
||||
let mut tags = vec![
|
||||
vec!["-".into()],
|
||||
vec!["p".into(), subject.clone()],
|
||||
vec!["replaced-by".into(), replacement.clone()],
|
||||
];
|
||||
if kind == 8002 {
|
||||
tags.push(vec!["consent".into(), "relay".into()]);
|
||||
}
|
||||
let event = f.event(f.community, signer, kind, tags, "").await;
|
||||
event.verify().unwrap();
|
||||
let community = buzz_core::CommunityId::from_uuid(f.community);
|
||||
assert!(crate::archived_identities::archive(
|
||||
&f.pool,
|
||||
community,
|
||||
&subject,
|
||||
"self",
|
||||
&subject,
|
||||
None,
|
||||
Some(&replacement),
|
||||
&event.id.to_hex(),
|
||||
)
|
||||
.await
|
||||
.unwrap());
|
||||
assert!(
|
||||
crate::archived_identities::unarchive(&f.pool, community, &subject)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
assert!(
|
||||
!crate::archived_identities::is_archived(&f.pool, community, &subject)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
let before = export(&f.pool).await;
|
||||
for delete in [false, true] {
|
||||
let mut output = Vec::new();
|
||||
let result = f
|
||||
.store
|
||||
.run_profile_batches(&f.options(1), delete, None, &mut output)
|
||||
.await;
|
||||
assert!(result.is_err(), "kind {kind}, agent {agent}, delete {delete}: unresolved historical replacement was accepted");
|
||||
let error = result.unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("shared-history disposition required"),
|
||||
"{error}"
|
||||
);
|
||||
assert!(!String::from_utf8(output)
|
||||
.unwrap()
|
||||
.contains("delete_complete"));
|
||||
assert_eq!(
|
||||
before,
|
||||
export(&f.pool).await,
|
||||
"blocked cleanup mutated database"
|
||||
);
|
||||
}
|
||||
// The same historical reference in another community does not block cleanup here.
|
||||
sqlx::query("UPDATE events SET community_id=$2 WHERE community_id=$1 AND id=$3")
|
||||
.bind(f.community)
|
||||
.bind(f.elsewhere)
|
||||
.bind(event.id.to_bytes().as_slice())
|
||||
.execute(&f.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let foreign = export(&f.pool).await;
|
||||
f.store
|
||||
.run_profile_batches(&f.options(1), true, None, &mut Vec::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(foreign["events"], export(&f.pool).await["events"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires Postgres"]
|
||||
async fn historical_archive_request_replacement_blocks_after_unarchive() {
|
||||
historical_replacement_blocks_cleanup_after_unarchive(9035).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires Postgres"]
|
||||
async fn historical_archive_delta_replacement_blocks_after_unarchive() {
|
||||
historical_replacement_blocks_cleanup_after_unarchive(8002).await;
|
||||
}
|
||||
156
crates/buzz-db/src/store/user_deletion/profile_batches/rows.rs
Normal file
156
crates/buzz-db/src/store/user_deletion/profile_batches/rows.rs
Normal file
@@ -0,0 +1,156 @@
|
||||
use super::*;
|
||||
use sqlx::Row;
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub(super) struct Table {
|
||||
pub name: &'static str,
|
||||
key: &'static str,
|
||||
identity: &'static str,
|
||||
pub selector: &'static str,
|
||||
}
|
||||
|
||||
pub(super) struct Operation {
|
||||
pub table: &'static Table,
|
||||
pub key: Value,
|
||||
pub fingerprint: String,
|
||||
pub snapshot: Option<events::Snapshot>,
|
||||
}
|
||||
impl Operation {
|
||||
pub fn cost(&self) -> usize {
|
||||
if self.snapshot.is_some() {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
}
|
||||
}
|
||||
pub fn description(&self) -> Value {
|
||||
json!({"table":self.table.name,"key":self.key,
|
||||
"action":if self.snapshot.is_some() {"replace_archive_snapshot"} else {"delete"}})
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) const EVENTS: Table = Table {
|
||||
name: "events",
|
||||
key: "jsonb_build_object('id',t.id,'created_at',t.created_at)",
|
||||
identity: "id=($2->>'id')::bytea AND created_at=($2->>'created_at')::timestamptz",
|
||||
selector: "t.id=ANY($3::bytea[])",
|
||||
};
|
||||
pub(super) const HEADS: Table = Table {
|
||||
name: "nip_fi_profile_heads",
|
||||
key: "jsonb_build_object('pubkey',t.pubkey)",
|
||||
identity: "pubkey=$2->>'pubkey'",
|
||||
selector: "t.pubkey=ANY(SELECT encode(k,'hex') FROM unnest($2::bytea[]) k)",
|
||||
};
|
||||
pub(super) const ARCHIVES: Table = Table {
|
||||
name: "archived_identities",
|
||||
key: "jsonb_build_object('pubkey',t.pubkey)",
|
||||
identity: "pubkey=$2->>'pubkey'",
|
||||
selector: HEADS.selector,
|
||||
};
|
||||
pub(super) const USERS: Table = Table {
|
||||
name: "users",
|
||||
key: "jsonb_build_object('pubkey',t.pubkey)",
|
||||
identity: "pubkey=($2->>'pubkey')::bytea",
|
||||
selector: "t.pubkey=ANY($2::bytea[])",
|
||||
};
|
||||
|
||||
pub(super) const CHILDREN: &[Table] = &[
|
||||
Table { name:"event_mentions", key:"jsonb_build_object('pubkey_hex',t.pubkey_hex,'event_id',t.event_id)",
|
||||
identity:"pubkey_hex=$2->>'pubkey_hex' AND event_id=($2->>'event_id')::bytea", selector:"t.event_id=ANY($3::bytea[])" },
|
||||
Table { name:"reactions", key:"jsonb_build_object('event_created_at',t.event_created_at,'event_id',t.event_id,'pubkey',t.pubkey,'emoji',t.emoji)",
|
||||
identity:"event_created_at=($2->>'event_created_at')::timestamptz AND event_id=($2->>'event_id')::bytea AND pubkey=($2->>'pubkey')::bytea AND emoji=$2->>'emoji'",
|
||||
selector:"t.event_id=ANY($3::bytea[]) OR t.reaction_event_id=ANY($3::bytea[])" },
|
||||
Table { name:"push_match_queue", key:"jsonb_build_object('event_id',t.event_id)", identity:"event_id=($2->>'event_id')::bytea", selector:"t.event_id=ANY($3::bytea[])" },
|
||||
Table { name:"push_wake_outbox", key:"jsonb_build_object('id',t.id)", identity:"id=($2->>'id')::uuid", selector:"t.event_id=ANY($3::bytea[])" },
|
||||
Table { name:"operator_listener_outbox", key:"jsonb_build_object('id',t.id)", identity:"id=($2->>'id')::uuid", selector:"t.event_id=ANY($3::bytea[])" },
|
||||
Table { name:"delivery_log", key:"jsonb_build_object('id',t.id,'delivered_at',t.delivered_at)", identity:"id=($2->>'id')::bigint AND delivered_at=($2->>'delivered_at')::timestamptz", selector:"t.event_id=ANY($3::bytea[])" },
|
||||
];
|
||||
|
||||
pub(super) async fn collect(
|
||||
conn: &mut PgConnection,
|
||||
plan: &mut Plan,
|
||||
table: &'static Table,
|
||||
ids: &[Vec<u8>],
|
||||
max: u32,
|
||||
) -> Result<()> {
|
||||
let sql = format!("SELECT {} AS key, encode(sha256(convert_to(to_jsonb(t)::text,'UTF8')),'hex') AS fingerprint FROM {} t \
|
||||
WHERE community_id=$1 AND ({}) AND cardinality($2::bytea[])>=0 AND cardinality($3::bytea[])>=0 \
|
||||
ORDER BY {} LIMIT $4", table.key, table.name, table.selector, table.key);
|
||||
let rows = sqlx::query(sqlx::AssertSqlSafe(sql))
|
||||
.bind(plan.scope.community)
|
||||
.bind(&plan.scope.bytes)
|
||||
.bind(ids)
|
||||
.bind((i64::from(max).saturating_sub(plan.ops.len() as i64) + 1).min(65_537))
|
||||
.fetch_all(conn)
|
||||
.await?;
|
||||
for row in rows {
|
||||
push(
|
||||
plan,
|
||||
Operation {
|
||||
table,
|
||||
key: row.try_get("key")?,
|
||||
fingerprint: row.try_get("fingerprint")?,
|
||||
snapshot: None,
|
||||
},
|
||||
max,
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn push(plan: &mut Plan, op: Operation, max: u32) -> Result<()> {
|
||||
if plan.ops.len() >= 65_536 {
|
||||
return Err(invalid(
|
||||
"profile plan exceeds 65536-operation memory budget; no deletion performed",
|
||||
));
|
||||
}
|
||||
if plan.ops.len() >= max as usize {
|
||||
return Err(invalid(
|
||||
"profile plan exceeds max-items; no deletion performed",
|
||||
));
|
||||
}
|
||||
// Keys are bounded; the full source payload never enters the plan or output.
|
||||
if serde_json::to_vec(&op.key)?.len() > 1024 {
|
||||
return Err(invalid("oversized profile row key"));
|
||||
}
|
||||
plan.ops.push(op);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn apply(
|
||||
tx: &mut crate::AdmittedTx,
|
||||
scope: &Scope,
|
||||
op: &Operation,
|
||||
replacements: &HashMap<String, nostr::Event>,
|
||||
) -> Result<()> {
|
||||
if op.table.name == "users" {
|
||||
let blockers = plan::dependencies(tx.conn(), scope).await?;
|
||||
if !blockers.is_empty() {
|
||||
return Err(invalid(format!(
|
||||
"identity removal blocked: {}",
|
||||
blockers.join(", ")
|
||||
)));
|
||||
}
|
||||
}
|
||||
let changed = if op.snapshot.is_some() {
|
||||
events::replace_snapshot(tx, scope, op, replacements).await?
|
||||
} else {
|
||||
let sql = format!(
|
||||
"DELETE FROM {} t WHERE community_id=$1 AND ({}) AND encode(sha256(convert_to(to_jsonb(t)::text,'UTF8')),'hex')=$3",
|
||||
op.table.name, op.table.identity
|
||||
);
|
||||
sqlx::query(sqlx::AssertSqlSafe(sql))
|
||||
.bind(scope.community)
|
||||
.bind(&op.key)
|
||||
.bind(&op.fingerprint)
|
||||
.execute(tx.conn())
|
||||
.await?
|
||||
.rows_affected()
|
||||
};
|
||||
if changed != 1 {
|
||||
return Err(invalid(
|
||||
"selected profile row changed; current batch rolled back; re-preview",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -12,6 +12,8 @@ pub enum Command {
|
||||
ContentBatches(content_batches::Args),
|
||||
/// Run media cleanup directly, without a workflow request.
|
||||
MediaBatches(media::Args),
|
||||
/// Preview or delete profiles in one community; deletion requires stopped writers.
|
||||
ProfileBatches(profile_batches::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.
|
||||
@@ -102,6 +104,7 @@ pub async fn run(command: Command) -> Result<i32> {
|
||||
let command = match command {
|
||||
Command::ContentBatches(args) => return content_batches::run_command(args).await,
|
||||
Command::MediaBatches(args) => return media::run(args).await,
|
||||
Command::ProfileBatches(args) => return profile_batches::run(args).await,
|
||||
command => command,
|
||||
};
|
||||
if let Command::AccountBatches(args) = command {
|
||||
@@ -150,7 +153,7 @@ pub async fn run(command: Command) -> Result<i32> {
|
||||
};
|
||||
let store = db.entity_deletion_store();
|
||||
match command {
|
||||
Command::ContentBatches(_) | Command::MediaBatches(_) => {
|
||||
Command::ContentBatches(_) | Command::MediaBatches(_) | Command::ProfileBatches(_) => {
|
||||
bail!("direct cleanup command dispatched above")
|
||||
}
|
||||
Command::AccountBatches(_) => anyhow::bail!("account command dispatched above"),
|
||||
@@ -247,6 +250,7 @@ mod inventory;
|
||||
pub mod media;
|
||||
/// Standalone delegation of an owned community to community deletion.
|
||||
pub mod owned_community;
|
||||
mod profile_batches;
|
||||
/// Read-only summaries of locally saved request progress and external waits.
|
||||
pub mod summary;
|
||||
mod transition;
|
||||
|
||||
117
crates/buzz-deletion/src/user/profile_batches.rs
Normal file
117
crates/buzz-deletion/src/user/profile_batches.rs
Normal file
@@ -0,0 +1,117 @@
|
||||
//! Standalone profile command. No workflow stages are enabled here.
|
||||
use anyhow::Result;
|
||||
use buzz_db::user_deletion::profile_batches::ProfileBatchOptions;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Scope and limits for offline profile cleanup.
|
||||
#[derive(Debug, clap::Args)]
|
||||
pub struct Args {
|
||||
/// Human public key (hex or npub); includes directly owned agents.
|
||||
#[arg(long, value_parser = parse_key)]
|
||||
pubkey: String,
|
||||
/// One explicit surviving community, including former memberships.
|
||||
#[arg(long)]
|
||||
community: Uuid,
|
||||
/// Trusted relay signer for verified profiles and archive events; repeatable.
|
||||
#[arg(long, value_parser = parse_key)]
|
||||
relay_pubkey: Vec<String>,
|
||||
/// Print proposed rows without writing anything (the default).
|
||||
#[arg(long, alias = "read-only", conflicts_with = "delete")]
|
||||
print_only: bool,
|
||||
/// Apply batches. Stop relay and external writers; finish content/account/media cleanup first.
|
||||
#[arg(long, conflicts_with = "print_only")]
|
||||
delete: bool,
|
||||
/// Maximum row mutations per transaction, 1–100.
|
||||
#[arg(long, default_value_t = 100, value_parser = clap::value_parser!(u16).range(1..=100))]
|
||||
batch_size: u16,
|
||||
/// Maximum planned row mutations; exceeding the limit fails before deletion.
|
||||
#[arg(long, default_value_t = 100_000, value_parser = clap::value_parser!(u32).range(1..=1_000_000))]
|
||||
max_items: u32,
|
||||
}
|
||||
|
||||
fn parse_key(value: &str) -> std::result::Result<String, String> {
|
||||
buzz_db::user_deletion::normalize_user_deletion_pubkey(value).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub(super) async fn run(args: Args) -> Result<i32> {
|
||||
let db = buzz_db::Db::connect_cold_start(
|
||||
buzz_db::DbConfig {
|
||||
database_url: crate::required_env("DATABASE_URL")?,
|
||||
max_connections: 1,
|
||||
min_connections: 0,
|
||||
default_transaction_read_only: !args.delete,
|
||||
..Default::default()
|
||||
},
|
||||
"profile_batches",
|
||||
)
|
||||
.await?;
|
||||
// Never parse, require or print a private key during preview.
|
||||
let secret = if args.delete {
|
||||
std::env::var("BUZZ_RELAY_PRIVATE_KEY").ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
db.user_deletion_store()
|
||||
.run_profile_batches(
|
||||
&ProfileBatchOptions {
|
||||
community: args.community,
|
||||
pubkey: args.pubkey,
|
||||
relay_pubkeys: args.relay_pubkey,
|
||||
batch_size: args.batch_size,
|
||||
max_items: args.max_items,
|
||||
},
|
||||
args.delete,
|
||||
secret.as_deref(),
|
||||
&mut std::io::stdout(),
|
||||
)
|
||||
.await?;
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use clap::Parser;
|
||||
#[derive(Parser)]
|
||||
struct Cli {
|
||||
#[command(flatten)]
|
||||
args: Args,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_is_default_and_delete_is_explicit() {
|
||||
let base = [
|
||||
"profile-batches",
|
||||
"--pubkey",
|
||||
"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
|
||||
"--community",
|
||||
"00000000-0000-0000-0000-000000000001",
|
||||
];
|
||||
for flag in [None, Some("--print-only"), Some("--read-only")] {
|
||||
assert!(
|
||||
!Cli::try_parse_from(base.into_iter().chain(flag))
|
||||
.unwrap()
|
||||
.args
|
||||
.delete
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
Cli::try_parse_from(base.into_iter().chain(["--delete"]))
|
||||
.unwrap()
|
||||
.args
|
||||
.delete
|
||||
);
|
||||
for flag in ["--print-only", "--read-only"] {
|
||||
assert!(Cli::try_parse_from(base.into_iter().chain([flag, "--delete"])).is_err());
|
||||
}
|
||||
for extra in [
|
||||
["--batch-size", "0"],
|
||||
["--batch-size", "101"],
|
||||
["--max-items", "0"],
|
||||
["--pubkey", "bad"],
|
||||
["--agent-pubkey", base[2]],
|
||||
] {
|
||||
assert!(Cli::try_parse_from(base.into_iter().chain(extra)).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
106
docs/profile-cleanup.md
Normal file
106
docs/profile-cleanup.md
Normal file
@@ -0,0 +1,106 @@
|
||||
# Standalone profile cleanup
|
||||
|
||||
`buzz-admin user-deletions profile-batches` previews or removes profile data in
|
||||
one explicit community. This is the identity step after content, account and
|
||||
media cleanup. It does not enable the user-deletion workflow or declare complete
|
||||
account erasure.
|
||||
|
||||
```sh
|
||||
# DATABASE_URL selects the operator database. Preview is the default.
|
||||
buzz-admin user-deletions profile-batches \
|
||||
--pubkey <human-hex-or-npub> --community <uuid> --print-only
|
||||
|
||||
# --read-only is an alias for --print-only.
|
||||
# Stop the relay and external writers and finish earlier cleanup first.
|
||||
buzz-admin user-deletions profile-batches \
|
||||
--pubkey <human-hex-or-npub> --community <uuid> --delete
|
||||
```
|
||||
|
||||
The human and directly owned agents are discovered afresh from `users` in the
|
||||
selected community on every preview, delete and retry. Ownership in another
|
||||
community never authorizes cleanup here. A changed ownership set or unselected
|
||||
child agent blocks a write batch. The output prints the discovered `target_pubkeys`
|
||||
for inspection; saved agent keys are not accepted as deletion authority.
|
||||
This command requires privileged database access.
|
||||
|
||||
The supported families are ordinary profiles (0/10100), owner-authored managed
|
||||
agent records (30177/30179), verified profiles (30382), archive requests and
|
||||
deltas (9035/9036/8002/8003), archive snapshots (13535), `nip_fi_profile_heads`,
|
||||
`archived_identities`, and final `users` rows. Event-dependent mention, reaction
|
||||
and delivery projections are removed before their source events. Agent identity
|
||||
rows go before the human row. Reserved kind 30179 is cleaned only if stored;
|
||||
this command does not enable its ingestion or decrypt its payload.
|
||||
|
||||
Verified profiles are selected by their matching `d`/`p` subject, not the event
|
||||
author. Supply `--relay-pubkey <hex-or-npub>` for each independently verified
|
||||
relay signer. A missing or untrusted signer stops the operation. The same trust
|
||||
rule applies to archive deltas and snapshots. Human-signed requests about another
|
||||
identity and archive actor/replacement references on surviving identities need
|
||||
an explicit shared-history disposition. Selected archive events with these
|
||||
references stop planning with an error before `profile_batches_start` is printed;
|
||||
they are not included in its blocker list. Historical `replaced-by` references in
|
||||
archive requests and deltas still stop planning after unarchive removes the
|
||||
canonical archive row.
|
||||
|
||||
Shared archive snapshots are rebuilt from the retained canonical archive rows.
|
||||
The snapshot replacement is a fresh signed event; no old signature is reused.
|
||||
Deletion requires `BUZZ_RELAY_PRIVATE_KEY` matching the affected snapshot signer.
|
||||
Preview never requires or reads this key. Historical snapshots that require a
|
||||
different signing key remain blocked pending reconciliation. Do not pass secrets
|
||||
on the command line or include them in logs.
|
||||
|
||||
Each JSON line describes the scope, proposed batch, committed batch, or final
|
||||
summary. Batches default to 100 row mutations; `--batch-size` accepts 1–100.
|
||||
Replacing a snapshot costs two mutations (delete and insert in one transaction),
|
||||
so it requires a batch size of at least two. `--max-items` defaults to 100,000;
|
||||
exceeding it fails before deletion. Additional memory limits cap a plan at 65,536
|
||||
operations and candidate tags at 32 MiB (64 KiB per event); archive snapshots
|
||||
support up to 10,000 retained identities. Exceeding any limit is an error, never
|
||||
a successful partial preview. SQL statements have a 30-second timeout and locks
|
||||
a three-second timeout; large accounts can require a separately reviewed plan.
|
||||
|
||||
Before mutations, the command rejects remaining credentials, memberships,
|
||||
workflows, subscriptions, non-profile authored content other than repository
|
||||
announcements/state (30617/30618), and unresolved archive references. Repository
|
||||
events and name mappings remain intact and do not block identity removal.
|
||||
It retains replay watermarks, deletion fences, requests, approvals,
|
||||
history, repositories and media objects. Media cleanup must preserve its source
|
||||
evidence before this command removes avatar/configuration references.
|
||||
|
||||
Each committed batch survives interruption. Rerun with the same human and community
|
||||
to discover the remaining agents. All profile data is removed before any identity
|
||||
row, so interruption during identity removal leaves no unfinished profile data
|
||||
for an agent that can no longer be discovered. Source fingerprints and the full
|
||||
current ownership set are rechecked inside the batch transaction; a mismatch rolls back that batch. A failure after commit
|
||||
but before output is an error and does not mean the batch rolled back. No success
|
||||
marker is printed if prerequisites or final profile checks fail. The final
|
||||
summary always has `account_erasure_complete: false`.
|
||||
|
||||
The stopped-writer requirement includes pending login-triggered verified-profile
|
||||
publication and external agent/config writers. This command does not add online
|
||||
admission fencing or invalidate client caches. Restart/refresh the supported
|
||||
serving processes and clients as part of the full deletion procedure. Retaining
|
||||
replay records alone does not prove every writer is fenced. Ordinary verified
|
||||
profiles remain historical records; explicit operator erasure is a separate
|
||||
exception to normal refresh behavior.
|
||||
|
||||
## Local verification
|
||||
|
||||
Use a disposable database and relay, following `TESTING.md`; do not reuse a
|
||||
Desktop database. Seed a human, two owned agents, a survivor, and a second
|
||||
community. Include ordinary/verified profiles, managed configuration and a
|
||||
shared archive snapshot. Complete content/account cleanup in the first community.
|
||||
|
||||
1. Export every table and the object inventory. Run print-only with the known
|
||||
relay public key. Compare every selected key with the expected inventory and
|
||||
confirm all exports are unchanged.
|
||||
2. Stop writers. Run delete with the same scope and relay signing key. Compare
|
||||
proposed and committed keys and the surviving data, including the second
|
||||
community. Verify the new shared snapshot signature and survivor list.
|
||||
3. Rerun with the same human and community; expect zero operations. Interrupt a
|
||||
multi-batch run and repeat to confirm recovery. Introduce an unresolved dependency or a
|
||||
wrong signer and confirm no deletion occurs.
|
||||
4. Restart the isolated relay and reload clients. Check profile-event queries,
|
||||
directory/name search and NIP-05. Test old-event replay and fresh admission
|
||||
under the full deletion procedure's write restrictions. Report any recreation;
|
||||
the standalone database result does not certify online enforcement.
|
||||
Reference in New Issue
Block a user