Skip to content

Commit 15d44dc

Browse files
TheSentinel454codexclaudeElrond
authored
Add owner deletion admission control plane (#7818)
## Summary Adds the relay and database admission boundary for owner-requested deletion of archived hosted communities. The operator endpoint records accepted owner intent with stable UUID idempotency and immutable owner/operator provenance. Admission serializes with unarchive and owner transfer, and accepted requests disappear from actionable owner listings. This keeps destructive execution out of the request path. The existing durable deletion engine remains the only executor, so this change adds no lifecycle state or second deletion mechanism. Complexity stays bounded: one durable request is both the idempotency record and the mutation fence. ### Related issue None found. ### Testing - `REDIS_URL=redis://127.0.0.1:6379 BUZZ_POSTGRES_ADMIN_URL=postgres://buzz:buzz_dev@localhost:5432/postgres PGHOST=localhost PGPORT=5432 PGUSER=buzz PGPASSWORD=buzz_dev PG_BIN_DIR=/tmp/buzz-pg-bin ./scripts/postgres-test-run.sh -p buzz-db -p buzz-relay --lib --tests` — 385 passed. - `cargo test -p buzz-db` — passed. - `cargo fmt --all -- --check` and `cargo clippy -p buzz-db -p buzz-relay --all-targets -- -D warnings` — passed. - `just desktop-test desktop-build desktop-tauri-check desktop-tauri-test web-build` — passed; Desktop ran 6,589 tests. - Full `just test` could not start uncached Keycloak dependencies because `quay.io` reset connections. Full `just ci` reached Flutter dependency resolution, then `pub.dev` reset connections. Generated with Codex --------- Signed-off-by: tornquist <[email protected]> Signed-off-by: Codex <[email protected]> Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Codex <[email protected]> Co-authored-by: Claude Opus 5 <[email protected]> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
1 parent 52c4c08 commit 15d44dc

13 files changed

Lines changed: 2602 additions & 90 deletions

File tree

‎ARCHITECTURE.md‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,43 @@ EVENT, REQ, REST, media, git, search, workflow, or pub/sub handling. Unknown
1414
hosts fail closed, and NIP-98/API-token stamps must agree with the host-derived
1515
community rather than overriding it.
1616

17+
Deployment-root community management uses operator-signed NIP-98 HTTP requests.
18+
`POST /operator/communities/delete` accepts only an exact normalized, archived
19+
community whose asserted pubkey is still its owner. The caller supplies the
20+
request UUID as the stable correlation/idempotency identity; the durable row
21+
records owner intent, mediating operator, and acknowledgement version. Admission
22+
returns `202` at the `submitted` stage and performs no inventory, approval,
23+
quiescing, object-store access, or deletion execution synchronously. While that
24+
non-aborted request exists, unarchive and ownership transfer conflict and owner
25+
management lists suppress the archived row. Replaying the same UUID converges
26+
to its current stage; a different UUID conflicts with the existing one-active-
27+
request invariant until that request is aborted.
28+
29+
Owner consent on this path is asserted, not proven. The mediating operator
30+
authenticates the owner and collects the deletion acknowledgement out of band,
31+
upstream of the relay; the request itself carries only the operator's NIP-98
32+
signature. The relay verifies operator authority and that the asserted pubkey
33+
is still the community's owner, then records the owner pubkey, mediating
34+
operator pubkey, and acknowledgement version as durable provenance for that
35+
upstream ceremony. No owner-signed attestation is required or checked, and
36+
owners have no self-service cancellation. Recovery is a privileged abort,
37+
which stays open across the reversible `submitted`, `inventoried`, `approved`,
38+
and `fenced` stages — releasing the request fence while leaving the community
39+
archived — and closes from `drained` onward, when tenant-state destruction may
40+
have begun.
41+
42+
Manual operator handoff converges on an admitted owner request only when
43+
`buzz-admin deletions submit --requested-by` repeats the owner pubkey recorded
44+
on the row. Owner provenance pins `requested_by` to `owner_pubkey`, so passing
45+
the operator's own pubkey does not converge — it conflicts with the existing
46+
one-active-request invariant instead.
47+
48+
Ownership is mutable only while a community is active. Archiving freezes the
49+
current owner. Normal transfer and deployment-root legacy convergence take the
50+
same community-row lock as owner-deletion admission, then reject archived,
51+
quiescing, deleted, or deletion-pending rotation without changing membership.
52+
Initial owner bootstrap for a newly created community remains supported.
53+
1754
Buzz is a Rust monorepo, licensed Apache 2.0 under Block, Inc.
1855

1956
---

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ pub use allowlist::AllowlistEntry;
7373
pub use api_token::{ApiTokenRecord, TokenSummary};
7474
pub use community::{
7575
ArchivedCommunityRecord, CommunityRecord, CreateCommunityWithOwnerResult,
76-
CreatedCommunityRecord, EnsuredCommunityRecord, OwnedCommunityRecord,
76+
CreatedCommunityRecord, EnsuredCommunityRecord, OwnedCommunityRecord, UnarchiveCommunityResult,
7777
UnarchivedCommunityRecord,
7878
};
7979
pub use error::{DbError, Result};

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

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -705,12 +705,17 @@ mod postgres_tests {
705705
let mut migrations: Vec<_> = MIGRATOR.iter().collect();
706706
migrations.sort_by_key(|migration| migration.version);
707707

708-
assert_eq!(migrations.len(), 50);
708+
assert_eq!(migrations.len(), 51);
709709
assert_eq!(migrations[48].version, 49);
710+
assert_eq!(migrations[50].version, 51);
710711
assert!(migrations[48]
711712
.sql
712713
.as_str()
713714
.contains("idx_thread_metadata_window"));
715+
assert!(migrations[50]
716+
.sql
717+
.as_str()
718+
.contains("community_deletion_owner_provenance"));
714719
assert_eq!(migrations[0].version, 1);
715720
assert_eq!(&*migrations[0].description, "initial schema");
716721
assert!(migrations[0]
@@ -1820,6 +1825,12 @@ mod postgres_tests {
18201825
.expect("embedded migration 0029")
18211826
.sql
18221827
.as_ref();
1828+
let migration_0051: &str = MIGRATOR
1829+
.iter()
1830+
.find(|migration| migration.version == 51)
1831+
.expect("embedded migration 0051")
1832+
.sql
1833+
.as_ref();
18231834
let workspace_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
18241835
.parent()
18251836
.and_then(std::path::Path::parent)
@@ -1828,6 +1839,7 @@ mod postgres_tests {
18281839
.expect("read schema/schema.sql");
18291840

18301841
let migration = surface(migration_0029);
1842+
let owner_admission_migration = surface(migration_0051);
18311843
let schema = surface(&schema_sql);
18321844

18331845
assert_eq!(
@@ -1856,13 +1868,42 @@ mod postgres_tests {
18561868
.functions
18571869
.get(function)
18581870
.unwrap_or_else(|| panic!("schema.sql is missing deletion function {function}"));
1859-
if function != "community_write_fence_excluded_table" {
1871+
if function != "community_write_fence_excluded_table"
1872+
&& function != "prevent_community_deletion_request_retargeting"
1873+
{
18601874
assert_eq!(
18611875
in_schema, definition,
18621876
"schema.sql definition of {function}() drifted from migration 0029"
18631877
);
18641878
}
18651879
}
1880+
assert_eq!(
1881+
schema
1882+
.functions
1883+
.get("prevent_community_deletion_request_retargeting")
1884+
.expect("schema.sql deletion retargeting guard"),
1885+
owner_admission_migration
1886+
.functions
1887+
.get("prevent_community_deletion_request_retargeting")
1888+
.expect("0051 deletion retargeting guard"),
1889+
"schema.sql must carry the latest immutable owner-provenance guard"
1890+
);
1891+
let request_table = schema
1892+
.tables
1893+
.get("community_deletion_requests")
1894+
.expect("schema.sql deletion request table");
1895+
for owner_provenance_fragment in [
1896+
"request_origin text not null default 'operator'",
1897+
"owner_pubkey text",
1898+
"mediating_operator_pubkey text",
1899+
"acknowledgement_version integer",
1900+
"constraint community_deletion_owner_provenance check",
1901+
] {
1902+
assert!(
1903+
request_table.contains(owner_provenance_fragment),
1904+
"schema.sql deletion requests are missing {owner_provenance_fragment}"
1905+
);
1906+
}
18661907
for (trigger, definition) in &migration.triggers {
18671908
let in_schema = schema
18681909
.triggers
@@ -2512,6 +2553,22 @@ mod postgres_tests {
25122553
assert_eq!(after, vec![(1, Some(true)), (30_179, None), (30_350, None)]);
25132554
}
25142555

2556+
/// Migration-upgrade half of the owner-provenance contract.
2557+
///
2558+
/// The desired-state bootstrap half lives in
2559+
/// `store::deletion::postgres_tests` and asserts the same shared case
2560+
/// table, so `schema/schema.sql` cannot admit owner rows the migration
2561+
/// path refuses (or the reverse).
2562+
#[tokio::test]
2563+
#[ignore = "requires Postgres"]
2564+
async fn migrated_schema_enforces_owner_provenance_contract() {
2565+
let pool = connect_test_pool().await;
2566+
reset_public_schema(&pool).await;
2567+
run_migrations(&pool).await.expect("run migrations");
2568+
2569+
crate::store::deletion::owner_provenance_contract::assert_contract(&pool).await;
2570+
}
2571+
25152572
#[tokio::test]
25162573
#[ignore = "requires Postgres"]
25172574
async fn run_migrations_applies_consolidated_initial_schema_on_fresh_database() {

‎crates/buzz-db/src/runtime/tests/thread_window_postgres_tests.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -311,7 +311,7 @@ async fn migration_schema_thread_window_prebuild_does_not_queue_behind_writer()
311311
production_result.is_ok(),
312312
"production migrator must preserve ingestion progress: {production_result:?}"
313313
);
314-
assert_eq!(version, 50);
314+
assert_eq!(version, 51);
315315
assert_eq!(final_oid, oid, "prebuild must not be replaced");
316316
assert_eq!(count, 4, "all writer witnesses must persist");
317317
}

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

Lines changed: 83 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,17 @@ pub struct UnarchivedCommunityRecord {
8181
pub host: String,
8282
}
8383

84+
/// Result of an owner-authorized unarchive attempt.
85+
#[derive(Debug, Clone, PartialEq, Eq)]
86+
pub enum UnarchiveCommunityResult {
87+
/// The community is active, with archive state cleared idempotently.
88+
Unarchived(UnarchivedCommunityRecord),
89+
/// Durable deletion intent exists and wins over restoration.
90+
DeletionPending,
91+
/// The host is absent, unavailable, or not owned by the asserted pubkey.
92+
NotFound,
93+
}
94+
8495
impl Db {
8596
/// Returns the community mapped to a normalized request host, if one exists.
8697
///
@@ -209,6 +220,10 @@ impl Db {
209220
JOIN relay_members rm ON rm.community_id = c.id
210221
WHERE rm.pubkey = $1
211222
AND rm.role = 'owner'
223+
AND NOT EXISTS (
224+
SELECT 1 FROM community_deletion_requests request
225+
WHERE request.community_id = c.id AND request.stage <> 'aborted'
226+
)
212227
ORDER BY c.created_at ASC, c.host ASC
213228
"#,
214229
)
@@ -531,40 +546,69 @@ impl Db {
531546
}
532547

533548
/// Idempotently restores a community when the asserted pubkey is its current owner.
549+
///
550+
/// Locks the community row so owner-deletion admission and restoration have
551+
/// one serial order. A non-aborted deletion request returns
552+
/// [`UnarchiveCommunityResult::DeletionPending`] without clearing archive state.
534553
#[datastore_span(name = "unarchive_community_owned_by", system = "postgresql")]
535554
pub async fn unarchive_community_owned_by(
536555
&self,
537556
normalized_host: &str,
538557
owner_pubkey: &str,
539-
) -> Result<Option<UnarchivedCommunityRecord>> {
540-
let mut connection = crate::observability::acquire_writer(
558+
) -> Result<UnarchiveCommunityResult> {
559+
let connection = crate::observability::acquire_writer(
541560
&self.pool,
542561
crate::observability::WriterOperation::Authorization,
543562
)
544563
.await?;
545-
let row = sqlx::query(
546-
r#"UPDATE communities c
547-
SET archived_at = NULL
548-
FROM relay_members rm
549-
WHERE lower(c.host) = lower($1)
550-
AND rm.community_id = c.id
551-
AND lower(rm.pubkey) = lower($2)
552-
AND rm.role = 'owner'
553-
AND c.deletion_state = 'active'
554-
AND c.deleted_at IS NULL
555-
RETURNING c.id, c.host"#,
564+
let mut tx = sqlx::Transaction::begin(connection, None).await?;
565+
let target = sqlx::query(
566+
"SELECT id, host FROM communities \
567+
WHERE lower(host) = lower($1) AND deletion_state = 'active' \
568+
AND deleted_at IS NULL FOR UPDATE",
556569
)
557570
.bind(normalized_host)
571+
.fetch_optional(&mut *tx)
572+
.await?;
573+
let Some(target) = target else {
574+
tx.rollback().await?;
575+
return Ok(UnarchiveCommunityResult::NotFound);
576+
};
577+
let community_id: Uuid = target.try_get("id")?;
578+
let is_owner: bool = sqlx::query_scalar(
579+
"SELECT EXISTS(SELECT 1 FROM relay_members \
580+
WHERE community_id = $1 AND lower(pubkey) = lower($2) AND role = 'owner')",
581+
)
582+
.bind(community_id)
558583
.bind(owner_pubkey)
559-
.fetch_optional(&mut *connection)
584+
.fetch_one(&mut *tx)
560585
.await?;
561-
row.map(|row| {
562-
Ok(UnarchivedCommunityRecord {
563-
id: CommunityId::from_uuid(row.try_get("id")?),
564-
host: row.try_get("host")?,
565-
})
566-
})
567-
.transpose()
586+
if !is_owner {
587+
tx.rollback().await?;
588+
return Ok(UnarchiveCommunityResult::NotFound);
589+
}
590+
let deletion_pending: bool = sqlx::query_scalar(
591+
"SELECT EXISTS(SELECT 1 FROM community_deletion_requests \
592+
WHERE community_id = $1 AND stage <> 'aborted')",
593+
)
594+
.bind(community_id)
595+
.fetch_one(&mut *tx)
596+
.await?;
597+
if deletion_pending {
598+
tx.rollback().await?;
599+
return Ok(UnarchiveCommunityResult::DeletionPending);
600+
}
601+
sqlx::query("UPDATE communities SET archived_at = NULL WHERE id = $1")
602+
.bind(community_id)
603+
.execute(&mut *tx)
604+
.await?;
605+
tx.commit().await?;
606+
Ok(UnarchiveCommunityResult::Unarchived(
607+
UnarchivedCommunityRecord {
608+
id: CommunityId::from_uuid(community_id),
609+
host: target.try_get("host")?,
610+
},
611+
))
568612
}
569613

570614
/// Returns the community that owns a channel, if the channel exists.
@@ -900,22 +944,26 @@ mod postgres_tests {
900944
.is_none(),
901945
"archived communities must fail admission"
902946
);
903-
assert!(db
904-
.unarchive_community_owned_by(&host, &outsider)
905-
.await
906-
.expect("wrong-owner unarchive")
907-
.is_none());
908-
assert!(db
909-
.unarchive_community_owned_by("missing.example", &owner)
910-
.await
911-
.expect("unknown-host unarchive")
912-
.is_none());
947+
assert_eq!(
948+
db.unarchive_community_owned_by(&host, &outsider)
949+
.await
950+
.expect("wrong-owner unarchive"),
951+
UnarchiveCommunityResult::NotFound
952+
);
953+
assert_eq!(
954+
db.unarchive_community_owned_by("missing.example", &owner)
955+
.await
956+
.expect("unknown-host unarchive"),
957+
UnarchiveCommunityResult::NotFound
958+
);
913959

914960
let restored = db
915961
.unarchive_community_owned_by(&host.to_ascii_uppercase(), &owner)
916962
.await
917-
.expect("unarchive community")
918-
.expect("owned community");
963+
.expect("unarchive community");
964+
let UnarchiveCommunityResult::Unarchived(restored) = restored else {
965+
panic!("expected owned community")
966+
};
919967
assert_eq!(restored.id, created.id);
920968
assert_eq!(restored.host, host);
921969
assert_eq!(
@@ -938,9 +986,8 @@ mod postgres_tests {
938986
let retry = db
939987
.unarchive_community_owned_by(&host, &owner)
940988
.await
941-
.expect("idempotent retry")
942-
.expect("owned community");
943-
assert_eq!(retry, restored);
989+
.expect("idempotent retry");
990+
assert_eq!(retry, UnarchiveCommunityResult::Unarchived(restored));
944991
}
945992

946993
#[tokio::test]

0 commit comments

Comments
 (0)