Skip to content

Commit 729233c

Browse files
committed
BUZZ-301: Add user deletion request intake
Signed-off-by: Ravneet Arora <[email protected]>
1 parent 5fefec6 commit 729233c

17 files changed

Lines changed: 551 additions & 8 deletions

‎Justfile‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -454,9 +454,9 @@ test-unit:
454454
-E 'test(=bucket_index::tests::bucket_snapshot_json_round_trip_preserves_community_keys)'
455455
# buzz-admin: storage-snapshot worker, the community archive command
456456
# parser, validation, and propagation-evidence tests, and the partition
457-
# audit outcome contract, and the NIP-FI binding command's policy loading and backfill report.
457+
# audit outcome contract, NIP-FI policy/backfill, and user-deletion intake.
458458
cargo nextest run -p buzz-admin \
459-
-E 'test(storage_snapshot) + test(/^communities::tests::/) + test(/^tests::communities_/) + test(=tests::partition_audit_outcomes_keep_their_json_names_and_exit_codes) + test(/^nip_fi::tests::/)'
459+
-E 'test(storage_snapshot) + test(/^communities::tests::/) + test(/^tests::communities_/) + test(=tests::partition_audit_outcomes_keep_their_json_names_and_exit_codes) + test(/^nip_fi::tests::/) + test(/^user_deletions::tests::/)'
460460
# Multi-tenant conformance gate (buzz-conformance): the independent
461461
# replay checker + golden fixtures. No infra — pure in-process trace
462462
# replay — so it belongs in the unit job. Run all targets (lib + the

‎crates/buzz-admin/src/main.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
mod communities;
2323
mod deletions;
2424
mod nip_fi;
25+
mod user_deletions;
2526

2627
use std::future::Future;
2728
use std::sync::atomic::{AtomicU64, Ordering};
@@ -126,6 +127,11 @@ enum Command {
126127
#[command(subcommand)]
127128
command: deletions::DeletionsCommand,
128129
},
130+
/// Submit and inspect synthetic user-deletion requests.
131+
UserDeletions {
132+
#[command(subcommand)]
133+
command: user_deletions::UserDeletionsCommand,
134+
},
129135
/// Emit missing kind:39000/39001/39002 channel discovery events, or
130136
/// republish only a targeted channel's kind:39002 roster.
131137
///
@@ -203,6 +209,7 @@ async fn run(cli: Cli) -> Result<i32> {
203209
} => cmd_list_product_feedback(limit).await,
204210
Command::Communities { command } => communities::run(command).await,
205211
Command::Deletions { command } => deletions::run(command).await,
212+
Command::UserDeletions { command } => user_deletions::run(command).await,
206213
Command::NipFi { command } => nip_fi::run(command).await,
207214
Command::ReconcileChannels { channel, relay_key } => {
208215
reconcile_channels(channel, relay_key).await?;
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
//! Thin `buzz-admin user-deletions` adapter.
2+
3+
pub use buzz_deletion::user::Command as UserDeletionsCommand;
4+
5+
/// Delegate request intake to the shared deletion crate.
6+
pub async fn run(command: UserDeletionsCommand) -> anyhow::Result<i32> {
7+
buzz_deletion::user::run(command).await
8+
}
9+
10+
#[cfg(test)]
11+
mod tests {
12+
use clap::Parser;
13+
14+
#[test]
15+
fn user_intake_commands_are_registered_without_execution() {
16+
for args in [
17+
vec![
18+
"buzz-admin",
19+
"user-deletions",
20+
"submit",
21+
"--target",
22+
"demo:alice",
23+
"--requested-by",
24+
"operator-a",
25+
],
26+
vec!["buzz-admin", "user-deletions", "list"],
27+
vec![
28+
"buzz-admin",
29+
"user-deletions",
30+
"inspect",
31+
"00000000-0000-0000-0000-000000000001",
32+
],
33+
] {
34+
assert!(crate::Cli::try_parse_from(args).is_ok());
35+
}
36+
for command in ["inventory", "approve", "run", "drain", "worker"] {
37+
assert!(crate::Cli::try_parse_from(["buzz-admin", "user-deletions", command]).is_err());
38+
}
39+
}
40+
}

‎crates/buzz-db/src/lib.rs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,10 +66,10 @@ pub(crate) use runtime::{
6666
};
6767
pub use store::{
6868
admin_moderation, allowlist, api_token, archived_identities, artifact, channel,
69-
channel_members, community, deletion, dm, event, feed, git_repo, moderation, nip_fi_binding,
70-
operator_listener, partition, personal_read, product_feedback, push, reaction, read_state,
71-
relay_admin_actions, relay_invite, relay_members, relay_operators, reminder, replaceable,
72-
storage_accounting, thread, thread_window, usage, user, workflow,
69+
channel_members, community, deletion, dm, entity_deletion, event, feed, git_repo, moderation,
70+
nip_fi_binding, operator_listener, partition, personal_read, product_feedback, push, reaction,
71+
read_state, relay_admin_actions, relay_invite, relay_members, relay_operators, reminder,
72+
replaceable, storage_accounting, thread, thread_window, usage, user, workflow,
7373
};
7474

7575
pub use allowlist::AllowlistEntry;

‎crates/buzz-db/src/runtime/migration.rs‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -483,6 +483,7 @@ mod postgres_tests {
483483
"product_feedback",
484484
"replica_heartbeat",
485485
"community_deletion_requests",
486+
"entity_deletion_requests",
486487
"community_deletion_approvals",
487488
"community_deletion_checkpoints",
488489
"community_deletion_manifest_keys",
@@ -709,7 +710,12 @@ mod postgres_tests {
709710
let mut migrations: Vec<_> = MIGRATOR.iter().collect();
710711
migrations.sort_by_key(|migration| migration.version);
711712

712-
assert_eq!(migrations.len(), 66);
713+
assert_eq!(migrations.len(), 67);
714+
assert_eq!(migrations[66].version, 67);
715+
assert!(migrations[66]
716+
.sql
717+
.as_str()
718+
.contains("CREATE TABLE entity_deletion_requests"));
713719
assert_eq!(migrations[64].version, 65);
714720
let retire_ttl = strip_sql_comments(migrations[64].sql.as_str());
715721
for statement in [
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
//! Operator-global intake for synthetic user-deletion requests.
2+
3+
use chrono::{DateTime, Utc};
4+
use serde::Serialize;
5+
use sqlx::PgPool;
6+
use uuid::Uuid;
7+
8+
use crate::{Db, DbError, Result};
9+
10+
/// A submitted demonstration request; no cleanup is authorized by this record.
11+
#[derive(Debug, Serialize, sqlx::FromRow)]
12+
pub struct EntityRequest {
13+
/// Stable request identifier.
14+
pub id: Uuid,
15+
/// Currently always `user`.
16+
pub entity_type: String,
17+
/// Synthetic `demo:` label, not a resolved account identity.
18+
pub target: String,
19+
/// Currently always `submitted`.
20+
pub status: String,
21+
/// Operator identity supplied at submission.
22+
pub requested_by: String,
23+
/// Optional explanation supplied at submission.
24+
pub reason: Option<String>,
25+
/// Time of the original submission.
26+
pub created_at: DateTime<Utc>,
27+
/// Time of the last change; identical resubmissions do not change it.
28+
pub updated_at: DateTime<Utc>,
29+
}
30+
31+
/// Writer-database access to synthetic deletion requests.
32+
#[derive(Clone)]
33+
pub struct EntityDeletionStore {
34+
pool: PgPool,
35+
}
36+
37+
impl Db {
38+
/// Use the writer pool for operator-global request intake and inspection.
39+
pub fn entity_deletion_store(&self) -> EntityDeletionStore {
40+
EntityDeletionStore {
41+
pool: self.pool().clone(),
42+
}
43+
}
44+
}
45+
46+
impl EntityDeletionStore {
47+
/// Save a request or return an identical previous submission.
48+
///
49+
/// A conflicting operator or reason returns an error without changing the
50+
/// existing request. Concurrent identical submissions converge on one row.
51+
pub async fn submit(
52+
&self,
53+
target: &str,
54+
requested_by: &str,
55+
reason: Option<&str>,
56+
) -> Result<EntityRequest> {
57+
validate_submission(target, requested_by, reason)?;
58+
let mut tx = self.pool.begin().await?;
59+
sqlx::query(
60+
"INSERT INTO entity_deletion_requests (target, requested_by, reason)
61+
VALUES ($1, $2, $3) ON CONFLICT (entity_type, target) DO NOTHING",
62+
)
63+
.bind(target)
64+
.bind(requested_by)
65+
.bind(reason)
66+
.execute(&mut *tx)
67+
.await?;
68+
let request: EntityRequest = sqlx::query_as(
69+
"SELECT * FROM entity_deletion_requests WHERE entity_type = 'user' AND target = $1",
70+
)
71+
.bind(target)
72+
.fetch_one(&mut *tx)
73+
.await?;
74+
if request.requested_by != requested_by || request.reason.as_deref() != reason {
75+
return Err(DbError::DeletionSafety(format!(
76+
"target already has request {}; inspect it before resubmission",
77+
request.id
78+
)));
79+
}
80+
tx.commit().await?;
81+
Ok(request)
82+
}
83+
84+
/// Load a request from the authoritative writer database.
85+
pub async fn get(&self, id: Uuid) -> Result<EntityRequest> {
86+
sqlx::query_as("SELECT * FROM entity_deletion_requests WHERE id = $1")
87+
.bind(id)
88+
.fetch_optional(&self.pool)
89+
.await?
90+
.ok_or_else(|| DbError::NotFound(format!("entity deletion request {id}")))
91+
}
92+
93+
/// List up to 1,000 requests, newest first.
94+
pub async fn list(&self, limit: u16) -> Result<Vec<EntityRequest>> {
95+
Ok(sqlx::query_as(
96+
"SELECT * FROM entity_deletion_requests ORDER BY created_at DESC, id LIMIT $1",
97+
)
98+
.bind(i64::from(limit.clamp(1, 1000)))
99+
.fetch_all(&self.pool)
100+
.await?)
101+
}
102+
}
103+
104+
fn validate_submission(target: &str, requested_by: &str, reason: Option<&str>) -> Result<()> {
105+
let slug = target.strip_prefix("demo:").unwrap_or_default();
106+
if slug.is_empty()
107+
|| slug.len() > 64
108+
|| !slug.as_bytes()[0].is_ascii_alphanumeric()
109+
|| !slug
110+
.bytes()
111+
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-')
112+
{
113+
return Err(DbError::DeletionSafety(
114+
"target must be demo:<1..64 lowercase letters, digits, underscores or hyphens>".into(),
115+
));
116+
}
117+
if requested_by.is_empty() || requested_by.len() > 256 || requested_by.trim() != requested_by {
118+
return Err(DbError::DeletionSafety(
119+
"operator identity must be 1..256 bytes without surrounding whitespace".into(),
120+
));
121+
}
122+
if reason.is_some_and(|r| r.len() > 4096) {
123+
return Err(DbError::DeletionSafety("reason exceeds 4096 bytes".into()));
124+
}
125+
Ok(())
126+
}
127+
128+
#[cfg(test)]
129+
#[path = "entity_deletion_postgres_tests.rs"]
130+
mod postgres_tests;

0 commit comments

Comments
 (0)