Skip to content

Commit 2c28e07

Browse files
authored
BUZZ-413: Add user deletion fence storage (#8632)
## Summary Add storage and lock helpers for the first user-deletion fencing PR. No serving handler or deletion worker calls these helpers yet, so this does not block users or enable real deletion. The operator-global `user_deletion_fences` table stores global user restrictions and community-scoped agent restrictions. Community and profile deletion retain these rows unchanged. `scope_community_id` records a restriction's scope; it does not make the row community-owned. The helpers use the caller's transaction, stable identity lock keys, ordered shared/exclusive locks, and indexed lookups. Inserts preserve the original request and owner on retry and reject conflicting provenance. Inserts validate the current worker lease and approved inventory through the existing entity-deletion guards. Callers must still verify that the target identities and agent ownership belong to the request. This is an additive schema expansion with a five-second migration lock timeout. It adds no database triggers, functions, foreign keys, or backfills. Both schema sources and operator-global registrations are updated. The unused request-ID index was removed. The existing community-deletion catalog and purge logic are unchanged. Tests cover live schema parity, concurrency, rollback, and retention through the existing purge and verification functions. ### Related issue Part of [BUZZ-413](https://linear.app/squareup/issue/BUZZ-413/gate-user-and-owned-agent-activity). This is the storage foundation; serving checks and real workflow handlers follow separately. No duplicate fence-storage PR found. ### Testing No manual app testing: these utilities have no application callers yet. Local PostgreSQL validation uses an isolated test container and the repository's per-test database runner. Passed 84 selected PostgreSQL tests covering fence authorization, concurrent inserts, schema parity, retention, community deletion, entity-deletion storage, and user discovery. The authorization regression also failed as expected when the insertion guard was temporarily removed; the guard was restored before the final run. Command: `scripts/postgres-test-run.sh -p buzz-db --lib -E 'test(/user_deletion_fences/) | test(/admin_schema_parity_between/) | test(/^store::deletion::postgres_tests::/) | test(/^store::entity_deletion::postgres_tests::/) | test(/^store::user_deletion::/)'` with the local test PostgreSQL connection and `PG_BIN_DIR` configured. The full `just test` run had one failure: `composition_tests::composition_log_does_not_leak_issuer_url` missed an expected log message. The same compiled test passed when rerun alone. No relay logging code is changed by this PR. The full local `just ci` run and all normal pre-push hooks passed on the updated branch. Generated with Codex --------- Signed-off-by: Ravneet Arora <[email protected]>
1 parent 9e18d17 commit 2c28e07

12 files changed

Lines changed: 883 additions & 4 deletions

File tree

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,8 @@ pub use store::{
6969
channel_members, community, deletion, dm, entity_deletion, event, feed, git_repo, moderation,
7070
nip_fi_binding, operator_listener, partition, personal_read, product_feedback, push, reaction,
7171
read_state, relay_admin_actions, relay_invite, relay_members, relay_operators, reminder,
72-
replaceable, storage_accounting, thread, thread_window, usage, user, user_deletion, workflow,
72+
replaceable, storage_accounting, thread, thread_window, usage, user, user_deletion,
73+
user_deletion_fences, workflow,
7374
};
7475

7576
pub use allowlist::AllowlistEntry;

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -549,6 +549,7 @@ mod postgres_tests {
549549
"entity_deletion_approvals",
550550
"entity_deletion_requests",
551551
"entity_deletion_stage_history",
552+
"user_deletion_fences",
552553
"community_deletion_approvals",
553554
"community_deletion_checkpoints",
554555
"community_deletion_manifest_keys",
@@ -775,7 +776,8 @@ mod postgres_tests {
775776
let mut migrations: Vec<_> = MIGRATOR.iter().collect();
776777
migrations.sort_by_key(|migration| migration.version);
777778

778-
assert_eq!(migrations.len(), 73);
779+
assert_eq!(migrations.len(), 74);
780+
assert_eq!(migrations[73].version, 74);
779781
assert_eq!(migrations[72].version, 73);
780782
assert_eq!(migrations[71].version, 72);
781783
assert_eq!(migrations[70].version, 71);
@@ -2905,6 +2907,7 @@ mod postgres_tests {
29052907
"entity_deletion_approvals",
29062908
"entity_deletion_requests",
29072909
"entity_deletion_stage_history",
2910+
"user_deletion_fences",
29082911
] {
29092912
assert_eq!(
29102913
columns(&desired, table).await,
@@ -2941,6 +2944,7 @@ mod postgres_tests {
29412944
for table in [
29422945
"entity_deletion_requests",
29432946
"entity_deletion_stage_history",
2947+
"user_deletion_fences",
29442948
"entity_deletion_approvals",
29452949
] {
29462950
assert_eq!(

‎crates/buzz-db/src/store/deletion.rs‎

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4400,6 +4400,116 @@ mod postgres_tests {
44004400
use sqlx::postgres::{PgConnectOptions, PgPoolOptions};
44014401
use std::str::FromStr;
44024402

4403+
#[tokio::test]
4404+
#[ignore = "requires Postgres"]
4405+
async fn user_fences_survive_community_and_profile_deletion() {
4406+
assert_user_fence_retention().await;
4407+
}
4408+
4409+
#[tokio::test]
4410+
#[ignore = "requires Postgres"]
4411+
async fn migration_schema_user_fences_survive_community_and_profile_deletion() {
4412+
assert_user_fence_retention().await;
4413+
}
4414+
4415+
async fn assert_user_fence_retention() {
4416+
use crate::user_deletion_fences::{self as fences, FenceIdentity};
4417+
let (db, store) = store().await;
4418+
let (request, inventory) = inventoried_request(&db, &store).await;
4419+
let entity = db
4420+
.user_deletion_store()
4421+
.submit("demo:fence-retention", "operator", None)
4422+
.await
4423+
.unwrap();
4424+
let entities = db.entity_deletion_store();
4425+
entities
4426+
.approve(
4427+
entity.id,
4428+
"approver",
4429+
entity.inventory_digest.as_deref().unwrap(),
4430+
)
4431+
.await
4432+
.unwrap();
4433+
let entity_lease = entities
4434+
.claim(entity.id, "fence-worker", Duration::from_secs(300))
4435+
.await
4436+
.unwrap()
4437+
.unwrap();
4438+
let human_key = nostr::Keys::generate().public_key();
4439+
let agent_key = nostr::Keys::generate().public_key();
4440+
let human = FenceIdentity::user(human_key);
4441+
let agent = FenceIdentity::agent(request.community_id, agent_key);
4442+
sqlx::query("INSERT INTO users (community_id, pubkey) VALUES ($1, $2)")
4443+
.bind(request.community_id.as_uuid())
4444+
.bind(human_key.to_bytes().to_vec())
4445+
.execute(&db.pool)
4446+
.await
4447+
.unwrap();
4448+
let mut tx = db.pool.begin().await.unwrap();
4449+
fences::lock_request(&mut tx, &entity_lease).await.unwrap();
4450+
fences::lock_exclusive(&mut tx, &[human, agent])
4451+
.await
4452+
.unwrap();
4453+
let global = fences::insert(&mut tx, human, &entity_lease, None)
4454+
.await
4455+
.unwrap();
4456+
let scoped = fences::insert(&mut tx, agent, &entity_lease, Some(human_key))
4457+
.await
4458+
.unwrap();
4459+
tx.commit().await.unwrap();
4460+
sqlx::query("DELETE FROM users WHERE community_id = $1 AND pubkey = $2")
4461+
.bind(request.community_id.as_uuid())
4462+
.bind(human_key.to_bytes().to_vec())
4463+
.execute(&db.pool)
4464+
.await
4465+
.unwrap();
4466+
let mut tx = db.pool.begin().await.unwrap();
4467+
assert_eq!(
4468+
fences::find(&mut tx, human).await.unwrap(),
4469+
Some(global.clone())
4470+
);
4471+
tx.commit().await.unwrap();
4472+
4473+
store.approve(request.id, "approver", None).await.unwrap();
4474+
let claim = store
4475+
.claim_specific(request.id, "executor", DEFAULT_LEASE_DURATION)
4476+
.await
4477+
.unwrap()
4478+
.unwrap();
4479+
store.begin_quiescing(&claim.lease).await.unwrap();
4480+
let generation = store.fence(&claim.lease).await.unwrap();
4481+
let token = LeaseToken {
4482+
fence_generation: Some(generation),
4483+
..claim.lease
4484+
};
4485+
store
4486+
.freeze_destructive_storage_manifest(&token, &inventory.storage)
4487+
.await
4488+
.unwrap();
4489+
store.mark_drained(&token).await.unwrap();
4490+
store
4491+
.mark_bindings_removed(&token, serde_json::json!({"keys": 0}))
4492+
.await
4493+
.unwrap();
4494+
store.purge_postgres(&token).await.unwrap();
4495+
// This database-only fixture models the external cache adapter's
4496+
// completion before exercising PostgreSQL's logical-absence verifier.
4497+
store
4498+
.mark_cache_purged(&token, serde_json::json!({"test_cache": "empty"}))
4499+
.await
4500+
.unwrap();
4501+
store
4502+
.verify_postgres_logically_deleted(&token)
4503+
.await
4504+
.unwrap();
4505+
// Full row equality also proves that scoped restrictions were not
4506+
// widened to global ones by clearing scope_community_id.
4507+
let mut tx = db.pool.begin().await.unwrap();
4508+
assert_eq!(fences::find(&mut tx, human).await.unwrap(), Some(global));
4509+
assert_eq!(fences::find(&mut tx, agent).await.unwrap(), Some(scoped));
4510+
tx.commit().await.unwrap();
4511+
}
4512+
44034513
async fn store() -> (Db, DeletionStore) {
44044514
let database_url = std::env::var("BUZZ_TEST_DATABASE_URL")
44054515
.or_else(|_| std::env::var("DATABASE_URL"))

‎crates/buzz-db/src/store/entity_deletion/leases.rs‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,10 @@ impl EntityDeletionStore {
140140
}
141141
}
142142

143-
pub(super) async fn lock_owned(tx: &mut Tx<'_>, lease: &EntityLease) -> Result<EntityRequest> {
143+
pub(in crate::store) async fn lock_owned(
144+
tx: &mut Tx<'_>,
145+
lease: &EntityLease,
146+
) -> Result<EntityRequest> {
144147
// Lock by id first, then check expiry after any wait for that lock. An old
145148
// snapshot/transaction start time must not extend a worker's authority.
146149
let request: EntityRequest = sqlx::query_as(sqlx::AssertSqlSafe(format!(
@@ -167,7 +170,7 @@ pub(super) async fn lock_owned(tx: &mut Tx<'_>, lease: &EntityLease) -> Result<E
167170
Ok(request)
168171
}
169172

170-
pub(super) async fn validate_approved_inventory(
173+
pub(in crate::store) async fn validate_approved_inventory(
171174
tx: &mut Tx<'_>,
172175
request: &EntityRequest,
173176
) -> Result<()> {

‎crates/buzz-db/src/store/entity_deletion/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ mod leases;
2525
pub(crate) mod requests;
2626
mod stages;
2727
pub use approvals::EntityApproval;
28+
pub(super) use leases::{lock_owned, validate_approved_inventory};
2829
pub use leases::{EntityExecution, EntityLease};
2930
pub use requests::{inventory_digest, EntityInspection, EntityRequest};
3031
use requests::{validate_operator, validated_inventory_digest};

‎crates/buzz-db/src/store/mod.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ pub(crate) mod event_follow_up;
2828
pub mod nip_fi_binding;
2929
/// User-specific deletion submission and inventory preparation.
3030
pub mod user_deletion;
31+
/// Operator-global user restrictions and identity-lock primitives.
32+
pub mod user_deletion_fences;
3133

3234
#[cfg(test)]
3335
mod event_follow_up_postgres_tests;

0 commit comments

Comments
 (0)