From 1a70c295e8f505184e92838815414e010979400b Mon Sep 17 00:00:00 2001 From: Will Pfleger Date: Wed, 18 Nov 2026 20:11:25 -0500 Subject: [PATCH 1/3] Revert "feat(relay): support community-scoped NIP-AR artifacts (#9650)" This reverts commit eebf62b61d22e5fbda482b34fd45f695fe341b15. Community scope adds a relay access gate outside channel membership and needs relay maintainer review before it ships. Reverting before migration 0097 reaches a deployed database keeps the revert free of a schema recovery step. Co-authored-by: Paul <4a1bfa0013bc6d14a8d600d8bf6392efefbd2a26ac3c96c9b2a106b0d12297ca@buzz.block.builderlab.xyz> Signed-off-by: Will Pfleger --- .env.example | 4 - crates/buzz-audit/src/service.rs | 22 +- crates/buzz-core/src/artifact.rs | 294 +------ crates/buzz-core/src/artifact_sync.rs | 24 +- crates/buzz-core/src/kind.rs | 4 - crates/buzz-db/src/lib.rs | 4 +- crates/buzz-db/src/runtime/migration.rs | 47 +- crates/buzz-db/src/runtime/mod.rs | 21 - crates/buzz-db/src/store/admin_moderation.rs | 7 +- crates/buzz-db/src/store/artifact.rs | 152 ++-- .../src/store/artifact_postgres_tests.rs | 588 ------------- crates/buzz-db/src/store/artifact_query.rs | 123 +-- crates/buzz-db/src/store/artifact_sync.rs | 6 +- .../buzz-db/src/store/community_artifact.rs | 659 -------------- crates/buzz-db/src/store/deletion.rs | 37 +- crates/buzz-db/src/store/event.rs | 53 +- crates/buzz-db/src/store/mod.rs | 2 - .../artifact_postgres_tests.rs | 217 ----- .../user_deletion/content_batches/execute.rs | 1 - .../user_deletion/content_batches/grouped.rs | 41 - .../user_deletion/content_batches/mod.rs | 9 +- .../user_deletion/content_batches/owned.rs | 5 - .../user_deletion/profile_batches/plan.rs | 1 - crates/buzz-db/tests/observability_source.rs | 1 - crates/buzz-pubsub/src/artifact_signal.rs | 59 -- crates/buzz-pubsub/src/lib.rs | 79 +- crates/buzz-pubsub/src/subscriber.rs | 15 - crates/buzz-pubsub/src/topic.rs | 6 - crates/buzz-relay/src/api/admin/mod.rs | 38 +- .../artifact_direct_postgres_tests.rs | 59 -- crates/buzz-relay/src/api/artifact.rs | 70 +- .../src/api/artifact_postgres_tests.rs | 29 +- .../community_postgres_tests.rs | 501 ----------- crates/buzz-relay/src/api/artifact_sync.rs | 4 +- crates/buzz-relay/src/api/bridge.rs | 41 +- crates/buzz-relay/src/config.rs | 12 - crates/buzz-relay/src/handlers/artifact.rs | 30 +- .../buzz-relay/src/handlers/artifact_sync.rs | 376 +------- .../handlers/artifact_sync_postgres_tests.rs | 2 - .../community_postgres_tests.rs | 817 ------------------ crates/buzz-relay/src/handlers/close.rs | 6 - .../src/handlers/community_artifact.rs | 325 ------- crates/buzz-relay/src/handlers/event.rs | 37 +- crates/buzz-relay/src/handlers/ingest.rs | 87 +- crates/buzz-relay/src/handlers/mod.rs | 2 - .../buzz-relay/src/handlers/side_effects.rs | 7 +- crates/buzz-relay/src/main.rs | 2 - crates/buzz-relay/src/nip11.rs | 8 - crates/buzz-relay/src/protocol.rs | 2 - crates/buzz-relay/src/state.rs | 5 - crates/buzz-relay/src/subscription.rs | 18 +- crates/buzz-search/src/query.rs | 7 +- .../tests/postgres_fts_integration.rs | 8 +- docs/community-artifact-rollout.md | 111 --- docs/nips/NIP-AR.md | 81 +- migrations/0097_community_artifact_expand.sql | 74 -- schema/tables/public/artifact_heads.sql | 10 +- schema/tables/public/artifact_revisions.sql | 5 - schema/tables/public/communities.sql | 1 - .../community-artifact-contract.sql | 43 - 60 files changed, 281 insertions(+), 5018 deletions(-) delete mode 100644 crates/buzz-db/src/store/community_artifact.rs delete mode 100644 crates/buzz-db/src/store/user_deletion/content_batches/artifact_postgres_tests.rs delete mode 100644 crates/buzz-pubsub/src/artifact_signal.rs delete mode 100644 crates/buzz-relay/src/api/admin/postgres_tests/artifact_direct_postgres_tests.rs delete mode 100644 crates/buzz-relay/src/api/artifact_postgres_tests/community_postgres_tests.rs delete mode 100644 crates/buzz-relay/src/handlers/artifact_sync_postgres_tests/community_postgres_tests.rs delete mode 100644 crates/buzz-relay/src/handlers/community_artifact.rs delete mode 100644 docs/community-artifact-rollout.md delete mode 100644 migrations/0097_community_artifact_expand.sql delete mode 100644 scripts/maintenance/community-artifact-contract.sql diff --git a/.env.example b/.env.example index 35d50f97f16..b18765b79e2 100644 --- a/.env.example +++ b/.env.example @@ -509,7 +509,3 @@ BUZZ_NIP_FI_CHANGES=false BUZZ_MEMBERSHIP_SNAPSHOT_ENABLED=false # Independent listed-open public membership lookup; also deploy disabled. BUZZ_MEMBERSHIP_PUBLIC_ENABLED=false - -# Enable community NIP-AR only after the separate operator contract. -# See docs/community-artifact-rollout.md. -BUZZ_COMMUNITY_ARTIFACTS_ENABLED=false diff --git a/crates/buzz-audit/src/service.rs b/crates/buzz-audit/src/service.rs index 13385220f24..3d2cb8d3648 100644 --- a/crates/buzz-audit/src/service.rs +++ b/crates/buzz-audit/src/service.rs @@ -54,24 +54,10 @@ impl AuditService { pub async fn log(&self, entry: NewAuditEntry) -> Result { let mut tx = self.pool.begin().await?; buzz_db::deletion::guard_community_write(&mut tx, entry.community_id).await?; - let result = Self::log_in_transaction(&mut tx, entry).await?; - tx.commit().await?; - Ok(result) - } - - /// Append on a caller's transaction so an administrative mutation and its - /// hash-chain audit entry commit together. Admission is rechecked here. - /// The caller owns commit/rollback, and must not hold an audit lock before - /// acquiring the mutation's policy/identity locks. - pub async fn log_in_transaction( - tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, - entry: NewAuditEntry, - ) -> Result { - buzz_db::deletion::guard_community_write(tx, entry.community_id).await?; let lock_key = format!("{AUDIT_LOCK_NAMESPACE}{}", entry.community_id); sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))") .bind(&lock_key) - .execute(&mut **tx) + .execute(&mut *tx) .await?; // The stored row keys on the raw UUID; the typed `CommunityId` on the @@ -85,7 +71,7 @@ impl AuditService { ORDER BY seq DESC LIMIT 1", ) .bind(community_id) - .fetch_optional(&mut **tx) + .fetch_optional(&mut *tx) .await?; let (prev_seq, prev_hash): (i64, Option>) = match head { @@ -133,9 +119,11 @@ impl AuditService { .bind(&audit_entry.detail) .bind(audit_entry.created_at) .bind(audit_entry.hash_version) - .execute(&mut **tx) + .execute(&mut *tx) .await?; + tx.commit().await?; + Ok(audit_entry) } diff --git a/crates/buzz-core/src/artifact.rs b/crates/buzz-core/src/artifact.rs index e1991517ba0..50e8f6070db 100644 --- a/crates/buzz-core/src/artifact.rs +++ b/crates/buzz-core/src/artifact.rs @@ -41,28 +41,13 @@ impl ArtifactOp { }) } } -/// Separate identity and audience classes within a tenant. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum ArtifactScope { - /// A home channel determines access (the legacy wire format). - #[default] - Channel, - /// An explicitly signed tenant determines access. - Community, -} -/// Maximum stored community type policies, including explicit `everyone` entries. -pub const MAX_COMMUNITY_POLICIES: usize = 256; /// The authoritative envelope, independent of any client's content schema. #[derive(Debug)] pub struct ArtifactEnvelope { /// Community-local stable identity. pub id: Uuid, - /// Explicit audience and identity class. - pub scope: ArtifactScope, - /// Signed tenant, present only for community scope. - pub community: Option, - /// Home channel, present only for channel scope. - pub home: Option, + /// Home channel. + pub home: Uuid, /// Immutable type name. pub artifact_type: String, /// Lifecycle operation. @@ -99,17 +84,7 @@ pub fn validate(event: &Event) -> Result { if event.tags.len() > MAX_TAGS { return Err("too many tags"); } - let names = [ - "ar", - "d", - "h", - "community", - "type", - "title", - "op", - "root", - "prev", - ]; + let names = ["ar", "d", "h", "type", "title", "op", "root", "prev"]; let mut fields = std::collections::HashMap::new(); let mut bytes = 0; for tag in event.tags.iter() { @@ -145,24 +120,20 @@ pub fn validate(event: &Event) -> Result { return Err("unsupported artifact envelope version"); } let id = canonical_uuid(field("d")?)?; - let home = fields.get("h").map(|s| canonical_uuid(s)).transpose()?; - let community = fields - .get("community") - .map(|s| canonical_uuid(s)) - .transpose()?; - let scope = match (home, community) { - (Some(_), None) => ArtifactScope::Channel, - (None, Some(_)) if !fields.contains_key("root") => ArtifactScope::Community, - _ => { - return Err("exactly one channel or community scope is required; community omits root") - } - }; + let home = canonical_uuid(field("h")?)?; let artifact_type = field("type")?; - validate_type(artifact_type)?; - let op = ArtifactOp::parse(field("op")?).ok_or("invalid artifact operation")?; - if scope == ArtifactScope::Community && op == ArtifactOp::Move { - return Err("community artifacts cannot move"); + if artifact_type.len() > 128 + || !artifact_type.contains('.') + || !artifact_type.split('.').all(|c| { + !c.is_empty() + && c.as_bytes()[0].is_ascii_lowercase() + && c.bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-') + }) + { + return Err("invalid namespaced artifact type"); } + let op = ArtifactOp::parse(field("op")?).ok_or("invalid artifact operation")?; let prev = fields.get("prev").map(|s| event_id(s)).transpose()?; if (op == ArtifactOp::Create) != prev.is_none() { return Err("prev required exactly on non-create revisions"); @@ -187,8 +158,6 @@ pub fn validate(event: &Event) -> Result { } Ok(ArtifactEnvelope { id, - scope, - community, home, artifact_type: artifact_type.into(), op, @@ -263,7 +232,6 @@ mod tests { json!({"kinds":[45010],"#project":["p"]}), json!({"ids":["a"],"#project":["p"]}), json!({"kinds":"x","#project":["p"]}), - json!({"scope":"community"}), ] { assert!( matches!(route_filter(&rejected), FilterRoute::Rejected(_)), @@ -315,15 +283,11 @@ pub enum ArtifactView { /// The current revision of each artifact named by `#d`, including a /// deletion. Head, - /// Current community type write policy, selected by one exact `#type`. - Policy, } /// Explicit HTTP artifact query. All `#name` predicates compare the first /// value of the same tag. #[derive(Debug)] pub struct ArtifactQuery { - /// Explicit audience and identity class. - pub scope: ArtifactScope, /// Query view. pub view: ArtifactView, /// Exact tag-name/value predicates. @@ -352,9 +316,6 @@ pub fn route_filter(value: &serde_json::Value) -> FilterRoute { if value.get("artifact").is_some() { return FilterRoute::Artifact; } - if value.get("scope").and_then(serde_json::Value::as_str) == Some("community") { - return FilterRoute::Rejected("community scope requires an explicit artifact view"); - } let artifact_kind = value.get("kinds").is_none_or(|k| { k.as_array() .is_none_or(|ks| ks.iter().any(|k| matches!(k.as_u64(), Some(45010 | 45011)))) @@ -378,20 +339,9 @@ pub fn parse_query(value: &serde_json::Value) -> Result ArtifactView::Current, Some("history") => ArtifactView::History, Some("head") => ArtifactView::Head, - Some("policy") => ArtifactView::Policy, _ => return Err("artifact must be \"current\", \"history\" or \"head\""), }; - let scope = parse_scope(object)?; - let tags = parse_predicates(object, &["artifact", "scope", "kinds", "limit", "offset"])?; - if scope == ArtifactScope::Community && tags.iter().any(|(n, _)| n == "h") { - return Err("community scope forbids #h"); - } - if view == ArtifactView::Policy { - if scope != ArtifactScope::Community || object.len() != 3 { - return Err("policy requires only artifact, scope and one exact #type"); - } - exact_type(&tags)?; - } + let tags = parse_predicates(object, &["artifact", "kinds", "limit", "offset"])?; let number = |name: &str, default: u64| { object .get(name) @@ -404,13 +354,10 @@ pub fn parse_query(value: &serde_json::Value) -> Result MAX_PAGE_SIZE as u64 || offset > MAX_OFFSET { return Err("artifact page limit exceeded"); } - if matches!(view, ArtifactView::Head | ArtifactView::History) - && !tags.iter().any(|(n, _)| n == "d") - { + if view != ArtifactView::Current && !tags.iter().any(|(n, _)| n == "d") { return Err("history and head require #d"); } Ok(ArtifactQuery { - scope, view, tags, limit: limit as i64, @@ -460,210 +407,3 @@ pub(crate) fn parse_predicates( } Ok(tags) } - -/// Validate a canonical namespaced artifact type. -pub fn validate_type(value: &str) -> Result<(), &'static str> { - if value.len() > 128 - || !value.contains('.') - || !value.split('.').all(|c| { - !c.is_empty() - && c.as_bytes()[0].is_ascii_lowercase() - && c.bytes() - .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-') - }) - { - return Err("invalid namespaced artifact type"); - } - Ok(()) -} -/// Parse an explicit scope; omitted scope preserves channel behavior. -pub fn parse_scope( - object: &serde_json::Map, -) -> Result { - match object.get("scope") { - None => Ok(ArtifactScope::Channel), - Some(v) if v.as_str() == Some("community") => Ok(ArtifactScope::Community), - _ => Err("scope must be community or absent"), - } -} -/// Require one exact canonical type predicate. -pub fn exact_type(tags: &[(String, Vec)]) -> Result<&str, &'static str> { - let values = &tags - .iter() - .find(|(n, _)| n == "type") - .ok_or("one exact #type required")? - .1; - let [value] = values.as_slice() else { - return Err("one exact #type required"); - }; - validate_type(value)?; - Ok(value) -} -/// A signed community type policy compare-and-set command. -#[derive(Debug)] -pub struct ArtifactTypePolicyCommand { - /// Signed canonical tenant. - pub community: Uuid, - /// Canonical type. - pub artifact_type: String, - /// `everyone` or `admins`. - pub policy: String, - /// Expected command ID; `None` represents the wire value `0`. - pub prev: Option, -} -/// Validate kind 9034 without interpreting content as authority. -pub fn parse_policy_command(event: &Event) -> Result { - if event.kind.as_u16() != 9034 || !event.content.is_empty() || event.tags.len() != 4 { - return Err( - "policy command requires empty content and exactly community, type, policy and prev", - ); - } - let mut fields = std::collections::HashMap::new(); - for tag in event.tags.iter() { - let [name, value] = tag.as_slice() else { - return Err("policy tags require exactly two elements"); - }; - if !["community", "type", "policy", "prev"].contains(&name.as_str()) - || fields.insert(name.as_str(), value.as_str()).is_some() - { - return Err("invalid or repeated policy command tag"); - } - } - let field = |name| { - fields - .get(name) - .copied() - .ok_or("missing policy command tag") - }; - let community = canonical_uuid(field("community")?)?; - let artifact_type = field("type")?; - validate_type(artifact_type)?; - let policy = field("policy")?; - if !["everyone", "admins"].contains(&policy) { - return Err("invalid artifact write policy"); - } - let prev = field("prev")?; - let prev = if prev == "0" { - None - } else { - event_id(prev)?; - Some(prev.to_owned()) - }; - Ok(ArtifactTypePolicyCommand { - community, - artifact_type: artifact_type.into(), - policy: policy.into(), - prev, - }) -} - -#[cfg(test)] -mod community_tests { - use super::*; - use nostr::{EventBuilder, Keys, Kind, Tag}; - use serde_json::json; - fn signed(kind: u16, tags: Vec>, content: &str) -> Event { - EventBuilder::new(Kind::Custom(kind), content) - .tags(tags.into_iter().map(|tag| Tag::parse(tag).unwrap())) - .sign_with_keys(&Keys::generate()) - .unwrap() - } - fn tags() -> Vec> { - vec![ - vec!["ar".into(), "1".into()], - vec!["d".into(), Uuid::new_v4().to_string()], - vec!["community".into(), Uuid::new_v4().to_string()], - vec!["type".into(), "example.settings".into()], - vec!["title".into(), "Settings".into()], - vec!["op".into(), "create".into()], - ] - } - #[test] - fn signed_scope_is_exclusive_canonical_and_immovable() { - let valid = tags(); - let envelope = validate(&signed(45010, valid.clone(), "{}")).unwrap(); - assert_eq!(envelope.scope, ArtifactScope::Community); - assert!(envelope.home.is_none()); - for extra in [ - vec!["h".into(), Uuid::new_v4().to_string()], - valid[2].clone(), - vec!["root".into(), "a".repeat(64)], - ] { - let mut invalid = valid.clone(); - invalid.push(extra); - assert!(validate(&signed(45010, invalid, "{}")).is_err()); - } - let mut missing = valid.clone(); - missing.remove(2); - assert!(validate(&signed(45010, missing, "{}")).is_err()); - for community in [ - Uuid::new_v4().simple().to_string(), - Uuid::new_v4().to_string().to_uppercase(), - Uuid::nil().to_string(), - ] { - let mut invalid = valid.clone(); - invalid[2][1] = community; - assert!(validate(&signed(45010, invalid, "{}")).is_err()); - } - let mut moved = valid; - moved[5][1] = "move".into(); - moved.push(vec!["prev".into(), "a".repeat(64)]); - assert!(validate(&signed(45010, moved, "{}")).is_err()); - } - #[test] - fn policy_command_and_explicit_queries_are_strict() { - let valid = vec![ - vec!["community".into(), Uuid::new_v4().to_string()], - vec!["type".into(), "example.settings".into()], - vec!["policy".into(), "everyone".into()], - vec!["prev".into(), "0".into()], - ]; - assert!(parse_policy_command(&signed(9034, valid.clone(), "")) - .unwrap() - .prev - .is_none()); - assert!(parse_policy_command(&signed(9034, valid.clone(), "{}")).is_err()); - for extra in [ - valid[0].clone(), - vec!["h".into(), Uuid::new_v4().to_string()], - ] { - let mut invalid = valid.clone(); - invalid.push(extra); - assert!(parse_policy_command(&signed(9034, invalid, "")).is_err()); - } - for value in [ - json!({"artifact":"policy","scope":"community","#type":["example.settings"]}), - json!({"artifact":"current","scope":"community","#type":["example.settings"]}), - json!({"artifact":"head","scope":"community","#d":[Uuid::new_v4()]}), - ] { - assert_eq!(parse_query(&value).unwrap().scope, ArtifactScope::Community); - } - for invalid in [ - json!({"artifact":"policy","#type":["example.settings"]}), - json!({"artifact":"policy","scope":"community","#type":["example.a","example.b"]}), - json!({"artifact":"head","scope":"community"}), - json!({"artifact":"current","scope":"community","#h":[Uuid::new_v4()]}), - json!({"artifact":"current","scope":"unknown"}), - ] { - assert!(parse_query(&invalid).is_err(), "{invalid}"); - } - let valid = json!({"artifact":"current","scope":"community","#type":["example.settings"]}); - assert!(crate::artifact_sync::parse_sync(&valid).is_ok()); - for extra in [ - json!({"limit":1}), - json!({"offset":0}), - json!({"#h":[Uuid::new_v4()]}), - json!({"#type":[]}), - ] { - let mut invalid = valid.clone(); - invalid - .as_object_mut() - .unwrap() - .extend(extra.as_object().unwrap().clone()); - assert!( - crate::artifact_sync::parse_sync(&invalid).is_err(), - "{invalid}" - ); - } - } -} diff --git a/crates/buzz-core/src/artifact_sync.rs b/crates/buzz-core/src/artifact_sync.rs index bbcb8b6605b..87f63d417eb 100644 --- a/crates/buzz-core/src/artifact_sync.rs +++ b/crates/buzz-core/src/artifact_sync.rs @@ -1,7 +1,7 @@ //! NIP-AR sync filter: `{"artifact":"current", "#h":[...], ...}` on a `REQ`. //! The same current-state filter as HTTP `/query`; the `REQ` transport makes //! it a sync (complete set, `EOSE`, then live heads). -use crate::artifact::{canonical_uuid, exact_type, parse_predicates, parse_scope, ArtifactScope}; +use crate::artifact::{canonical_uuid, parse_predicates}; use uuid::Uuid; /// Largest set one sync serves: it bounds each initial read and the held @@ -12,8 +12,6 @@ pub const MAX_SYNC_EVENTS: usize = 4096; /// `#name` predicate, `#h` included, with NIP-AR match semantics. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ArtifactSyncFilter { - /// Explicit identity and audience class. - pub scope: ArtifactScope, /// Named channels (`#h`), deduplicated in request order. Never empty. pub channels: Vec, /// Exact tag-name/value predicates (AND across names, OR within one). @@ -50,19 +48,7 @@ pub fn parse_sync(value: &serde_json::Value) -> Result Result bool { | RELAY_ADMIN_REMOVE_MEMBER | RELAY_ADMIN_CHANGE_ROLE | RELAY_ADMIN_SET_WORKSPACE_PROFILE - | RELAY_ADMIN_SET_ARTIFACT_TYPE_POLICY ) } diff --git a/crates/buzz-db/src/lib.rs b/crates/buzz-db/src/lib.rs index 3369665cf81..106b46eda36 100644 --- a/crates/buzz-db/src/lib.rs +++ b/crates/buzz-db/src/lib.rs @@ -95,8 +95,8 @@ pub(crate) use runtime::{ }; pub use store::{ admin_moderation, allowlist, api_token, archived_identities, artifact, artifact_sync, channel, - channel_members, community, community_artifact, community_auth, deletion, dm, entity_deletion, - event, feed, git_repo, leader_lock, media, membership_snapshot, moderation, nip_fi_binding, + channel_members, community, community_auth, deletion, dm, entity_deletion, event, feed, + git_repo, leader_lock, media, membership_snapshot, moderation, nip_fi_binding, operator_listener, partition, personal_read, product_feedback, push, reaction, read_state, relay_admin_actions, relay_invite, relay_members, relay_operators, reminder, replaceable, storage_accounting, thread, thread_window, user, user_deletion, user_deletion_fences, workflow, diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index 4946d9394aa..bf2e65361ec 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -879,7 +879,7 @@ mod postgres_tests { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); migrations.sort_by_key(|migration| migration.version); - assert_eq!(migrations.len(), 97); + assert_eq!(migrations.len(), 96); assert_eq!(migrations[89].version, 90); assert!(migrations[89] .sql @@ -3100,51 +3100,6 @@ mod postgres_tests { .await .expect("apply migrations for schema parity"); - // Migration 0097 leaves the legacy conflict target available during - // the bridge rollout. Compare desired state after the operator contract. - { - let mut connection = migrated.acquire().await.expect("connect contract session"); - sqlx::query( - "SET buzz.community_artifact_contract_ready='all-backends-enforce-community-audience'", - ) - .execute(&mut *connection) - .await - .expect("attest fleet compatibility"); - sqlx::raw_sql(include_str!( - "../../../../scripts/maintenance/community-artifact-contract.sql" - )) - .execute(&mut *connection) - .await - .expect("contract the migrated artifact head key"); - } - let plan = pgschema( - &conn, - migrated_db.name(), - &["plan", "--output-json", "stdout"], - ); - assert!( - plan.status.success(), - "pgschema plan after artifact contract failed: {}\n{}", - String::from_utf8_lossy(&plan.stdout), - String::from_utf8_lossy(&plan.stderr), - ); - let plan: serde_json::Value = - serde_json::from_slice(&plan.stdout).expect("pgschema returns a structured plan"); - let head_changes: Vec<_> = plan["groups"] - .as_array() - .into_iter() - .flatten() - .flat_map(|group| group["steps"].as_array().expect("plan group has steps")) - .filter(|step| { - let path = step["path"].as_str().expect("plan step has an object path"); - path == "public.artifact_heads" || path.starts_with("public.artifact_heads.") - }) - .collect(); - assert!( - head_changes.is_empty(), - "pgschema planned artifact_heads changes after contract: {head_changes:?}" - ); - for table in [ "media_uploaders", "audit_log", diff --git a/crates/buzz-db/src/runtime/mod.rs b/crates/buzz-db/src/runtime/mod.rs index de12c606601..ebe7fb4a3f4 100644 --- a/crates/buzz-db/src/runtime/mod.rs +++ b/crates/buzz-db/src/runtime/mod.rs @@ -267,9 +267,6 @@ pub struct Db { /// Shared across clones; media authorization may use at most a quarter of /// the writer pool (capped at eight), leaving capacity for ordinary writes. pub(crate) media_authorization_slots: std::sync::Arc, - /// Long-lived community snapshots leave writer capacity for fresh enqueue - /// authorization. Shared across clones; one-connection pools refuse snapshots. - pub(crate) community_artifact_snapshots: std::sync::Arc, /// Optional bounded post-commit producer, shared across handle clones. pub(crate) push_enqueue: Option, /// Maximum connections configured for this pool (from [`DbConfig::max_connections`]). @@ -846,12 +843,6 @@ impl Db { .push_enabled .then(|| push_enqueue::PushEnqueue::new(&pool)); Ok(Self { - community_artifact_snapshots: std::sync::Arc::new(tokio::sync::Semaphore::new( - pool.options() - .get_max_connections() - .saturating_sub(1) - .min(8) as usize, - )), media_authorization_slots: media_authorization_slots(&pool), push_enqueue, pool, @@ -1399,12 +1390,6 @@ impl Db { /// that need push must use [`Db::new`] with `push_enabled` instead. pub fn from_pool(pool: PgPool) -> Self { Self { - community_artifact_snapshots: std::sync::Arc::new(tokio::sync::Semaphore::new( - pool.options() - .get_max_connections() - .saturating_sub(1) - .min(8) as usize, - )), media_authorization_slots: media_authorization_slots(&pool), push_enqueue: None, max_connections: pool.options().get_max_connections(), @@ -1428,12 +1413,6 @@ impl Db { /// [`Db::fence`]). pub fn from_pools(pool: PgPool, read_pool: PgPool) -> Self { Self { - community_artifact_snapshots: std::sync::Arc::new(tokio::sync::Semaphore::new( - pool.options() - .get_max_connections() - .saturating_sub(1) - .min(8) as usize, - )), media_authorization_slots: media_authorization_slots(&pool), push_enqueue: None, max_connections: pool.options().get_max_connections(), diff --git a/crates/buzz-db/src/store/admin_moderation.rs b/crates/buzz-db/src/store/admin_moderation.rs index 60eaa9523c9..a3a7e8c00e5 100644 --- a/crates/buzz-db/src/store/admin_moderation.rs +++ b/crates/buzz-db/src/store/admin_moderation.rs @@ -549,22 +549,19 @@ pub async fn get_event_preview( community_id: Uuid, id: &[u8], ) -> Result> { - let row = sqlx::query(concat!( + let row = sqlx::query( r#" SELECT id, pubkey, kind, content, created_at, deleted_at, channel_id FROM events WHERE community_id = $1 AND id = $2 AND kind <> ALL($3) AND pubkey <> ''::bytea - AND (kind <> 45010 OR (channel_id IS NOT NULL AND NOT "#, - crate::community_artifact_tag_sql!("tags"), - r#")) AND NOT (kind = 5 AND EXISTS ( SELECT 1 FROM jsonb_array_elements(tags) t WHERE t->>0 = 'k' AND t->>1 = ANY($4::text[]))) ORDER BY created_at DESC LIMIT 1 "#, - )) + ) .bind(community_id) .bind(id) .bind(admin_hidden_kinds()) diff --git a/crates/buzz-db/src/store/artifact.rs b/crates/buzz-db/src/store/artifact.rs index a7fd5293c0c..6f9f46eb174 100644 --- a/crates/buzz-db/src/store/artifact.rs +++ b/crates/buzz-db/src/store/artifact.rs @@ -4,27 +4,12 @@ //! before this transaction; here the relay only serializes each identity and //! compares the expected head. use crate::{Db, DbError, Result}; -use buzz_core::artifact::{ArtifactEnvelope, ArtifactOp, ArtifactScope}; +use buzz_core::artifact::{ArtifactEnvelope, ArtifactOp}; use buzz_core::{CommunityId, StoredEvent}; use nostr::{Event, EventBuilder, Keys, Kind, Tag}; -use sqlx::{PgConnection, Row}; +use sqlx::Row; use uuid::Uuid; -/// SQL predicate for an explicit `community` tag name in an event's tag column. -/// The containment prefilter also matches tag values, so recheck the first element. -#[macro_export] -macro_rules! community_artifact_tag_sql { - ($tags:literal) => { - concat!( - "(", - $tags, - r#" @> '[["community"]]'::jsonb AND jsonb_path_exists("#, - $tags, - r#", 'strict $[*] ? (@[0] == "community")', '{}'::jsonb, true))"#, - ) - }; -} - /// Acceptance outcome. Only a stale-`prev` conflict carries the current head, /// which the caller discloses after authorizing its channel. #[derive(Debug)] @@ -68,42 +53,6 @@ fn removal_marker(keys: &Keys, artifact: Uuid, source: Uuid, prev: &[u8]) -> Res .map_err(|e| invalid(&e.to_string())) } -pub(super) fn check_artifact_head( - env: &ArtifactEnvelope, - head: Option<&sqlx::postgres::PgRow>, -) -> Result> { - let outcome = match (head, env.op) { - (Some(_), ArtifactOp::Create) => ArtifactOutcome::Conflict("artifact identity is taken"), - (None, ArtifactOp::Create) => return Ok(None), - (None, _) => ArtifactOutcome::Conflict(HEAD_UNAVAILABLE), - (Some(head), op) => { - let current: Vec = head.try_get("event_id")?; - if env.prev.as_deref() != Some(current.as_slice()) { - ArtifactOutcome::Conflict("artifact head changed") - } else if env.artifact_type != head.try_get::("artifact_type")? { - ArtifactOutcome::Rejected("artifact type is immutable") - } else if head.try_get::("deleted")? != (op == ArtifactOp::Restore) { - ArtifactOutcome::Rejected( - "deleted artifacts require restore; live artifacts cannot restore", - ) - } else { - return Ok(None); - } - } - }; - Ok(Some(outcome)) -} - -pub(super) async fn artifact_receipt_exists( - conn: &mut PgConnection, - community: CommunityId, - event_id: &[u8], - scope: Option<&str>, -) -> Result { - Ok(sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM artifact_revisions WHERE community_id=$1 AND event_id=$2 AND ($3::text IS NULL OR scope=$3))") - .bind(community.as_uuid()).bind(event_id).bind(scope).fetch_one(conn).await?) -} - impl Db { /// Check the durable acceptance ledger, which survives redaction and retention. pub async fn artifact_accepted(&self, community: CommunityId, id: &[u8]) -> Result { @@ -112,7 +61,13 @@ impl Db { crate::observability::WriterOperation::EventWrite, ) .await?; - artifact_receipt_exists(&mut conn, community, id, None).await + Ok(sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM artifact_revisions WHERE community_id=$1 AND event_id=$2)", + ) + .bind(community.as_uuid()) + .bind(id) + .fetch_one(&mut *conn) + .await?) } /// Current home channel, read before authorizing a move's source. @@ -127,7 +82,7 @@ impl Db { ) .await?; Ok(sqlx::query_scalar( - "SELECT channel_id FROM artifact_heads WHERE community_id=$1 AND scope='channel' AND artifact_id=$2", + "SELECT channel_id FROM artifact_heads WHERE community_id=$1 AND artifact_id=$2", ) .bind(community.as_uuid()) .bind(artifact) @@ -147,12 +102,6 @@ impl Db { authorized_source: Option, relay_keys: &Keys, ) -> Result { - if env.scope != ArtifactScope::Channel { - return Ok(ArtifactOutcome::Rejected( - "community artifacts require explicit community admission", - )); - } - let home = env.home.ok_or_else(|| invalid("missing channel home"))?; let mut tx = self.begin_event_write_transaction(community).await?; sqlx::query("SET LOCAL statement_timeout='5s'") .execute(tx.conn()) @@ -162,11 +111,18 @@ impl Db { .bind(format!("artifact:{}:{}", community.as_uuid(), env.id)) .execute(tx.conn()) .await?; - if artifact_receipt_exists(tx.conn(), community, event.id.as_bytes(), None).await? { + let duplicate: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM artifact_revisions WHERE community_id=$1 AND event_id=$2)", + ) + .bind(community.as_uuid()) + .bind(event.id.as_bytes().as_slice()) + .fetch_one(tx.conn()) + .await?; + if duplicate { return Ok(ArtifactOutcome::Duplicate); } let head = sqlx::query( - "SELECT event_id,channel_id,artifact_type,root,deleted FROM artifact_heads WHERE community_id=$1 AND scope='channel' AND artifact_id=$2 FOR UPDATE", + "SELECT event_id,channel_id,artifact_type,root,deleted FROM artifact_heads WHERE community_id=$1 AND artifact_id=$2 FOR UPDATE", ) .bind(community.as_uuid()) .bind(env.id) @@ -176,33 +132,51 @@ impl Db { let old_root = head .as_ref() .and_then(|h| h.get::>, _>("root")); - // The caller authorized writes only in its home, or in the source - // it read before a move. Refuse a different source before describing the head. - let expected_source = if env.op == ArtifactOp::Move { - authorized_source - } else { - Some(home) - }; - if env.op != ArtifactOp::Create && source.is_some() && source != expected_source { - return Ok(ArtifactOutcome::Conflict(HEAD_UNAVAILABLE)); - } - if let Some(outcome) = check_artifact_head(env, head.as_ref())? { - return Ok(outcome); - } - if head.is_some() { - if (env.op == ArtifactOp::Move) != (source != Some(home)) { - return Ok(ArtifactOutcome::Rejected( - "only move changes home and move must change home", - )); + match (&head, env.op) { + (Some(_), ArtifactOp::Create) => { + return Ok(ArtifactOutcome::Conflict("artifact identity is taken")) + } + (None, ArtifactOp::Create) => {} + (None, _) => return Ok(ArtifactOutcome::Conflict(HEAD_UNAVAILABLE)), + // The caller authorized writes only in `h`, or for a move in the + // source it read before this transaction. A head anywhere else + // answers like a missing one, before any check that describes it. + (Some(_), op) + if source + != match op { + ArtifactOp::Move => authorized_source, + _ => Some(env.home), + } => + { + return Ok(ArtifactOutcome::Conflict(HEAD_UNAVAILABLE)) } - if env.op == ArtifactOp::Delete && env.root != old_root { - return Ok(ArtifactOutcome::Rejected("delete preserves root")); + (Some(head), op) => { + let current: Vec = head.get("event_id"); + if env.prev.as_deref() != Some(current.as_slice()) { + return Ok(ArtifactOutcome::Conflict("artifact head changed")); + } + if env.artifact_type != head.get::("artifact_type") { + return Ok(ArtifactOutcome::Rejected("artifact type is immutable")); + } + if head.get::("deleted") != (op == ArtifactOp::Restore) { + return Ok(ArtifactOutcome::Rejected( + "deleted artifacts require restore; live artifacts cannot restore", + )); + } + if (op == ArtifactOp::Move) != (source != Some(env.home)) { + return Ok(ArtifactOutcome::Rejected( + "only move changes home and move must change home", + )); + } + if op == ArtifactOp::Delete && env.root != old_root { + return Ok(ArtifactOutcome::Rejected("delete preserves root")); + } } } - if head.is_none() || env.root != old_root || source != Some(home) { + if head.is_none() || env.root != old_root || source != Some(env.home) { if let Some(root) = &env.root { let exists: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM events WHERE community_id=$1 AND id=$2 AND channel_id=$3 AND deleted_at IS NULL AND kind IN (9,40002,45001,45003))") - .bind(community.as_uuid()).bind(root).bind(home).fetch_one(tx.conn()).await?; + .bind(community.as_uuid()).bind(root).bind(env.home).fetch_one(tx.conn()).await?; if !exists { return Ok(ArtifactOutcome::Rejected( "root must be an existing conversation anchor in home", @@ -219,11 +193,11 @@ impl Db { .bind(if env.op == ArtifactOp::Move { source } else { None }) .execute(tx.conn()) .await?; - sqlx::query("INSERT INTO artifact_heads (community_id,artifact_id,event_id,channel_id,artifact_type,root,deleted,modified_at) VALUES ($1,$2,$3,$4,$5,$6,$7,clock_timestamp()) ON CONFLICT (community_id,scope,artifact_id) DO UPDATE SET event_id=EXCLUDED.event_id,channel_id=EXCLUDED.channel_id,root=EXCLUDED.root,deleted=EXCLUDED.deleted,modified_at=clock_timestamp()") - .bind(community.as_uuid()).bind(env.id).bind(event.id.as_bytes().as_slice()).bind(home).bind(&env.artifact_type).bind(&env.root).bind(env.op == ArtifactOp::Delete).execute(tx.conn()).await?; + sqlx::query("INSERT INTO artifact_heads (community_id,artifact_id,event_id,channel_id,artifact_type,root,deleted,modified_at) VALUES ($1,$2,$3,$4,$5,$6,$7,clock_timestamp()) ON CONFLICT (community_id,artifact_id) DO UPDATE SET event_id=EXCLUDED.event_id,channel_id=EXCLUDED.channel_id,root=EXCLUDED.root,deleted=EXCLUDED.deleted,modified_at=clock_timestamp()") + .bind(community.as_uuid()).bind(env.id).bind(event.id.as_bytes().as_slice()).bind(env.home).bind(&env.artifact_type).bind(&env.root).bind(env.op == ArtifactOp::Delete).execute(tx.conn()).await?; let (stored, _) = - crate::event::insert_event_in_transaction(&mut tx, event, Some(home)).await?; - crate::insert_mentions_in_transaction(&mut tx, event, Some(home)).await?; + crate::event::insert_event_in_transaction(&mut tx, event, Some(env.home)).await?; + crate::insert_mentions_in_transaction(&mut tx, event, Some(env.home)).await?; let mut accepted = vec![stored]; if let (ArtifactOp::Move, Some(source), Some(prev)) = (env.op, source, &env.prev) { let removal = removal_marker(relay_keys, env.id, source, prev)?; diff --git a/crates/buzz-db/src/store/artifact_postgres_tests.rs b/crates/buzz-db/src/store/artifact_postgres_tests.rs index b9812c1e8c5..f858deeb182 100644 --- a/crates/buzz-db/src/store/artifact_postgres_tests.rs +++ b/crates/buzz-db/src/store/artifact_postgres_tests.rs @@ -823,591 +823,3 @@ async fn sync_snapshot_pages_are_one_cut_and_head_includes_deletions() { .unwrap() .is_none()); } - -mod community { - use super::*; - use crate::community_artifact::{ - set_policy_in_transaction, CommunityArtifactPrincipal, PolicyOutcome, - }; - use crate::DbError; - use serde_json::json; - - async fn contract(f: &Fixture) { - let mut connection = f.db.pool.acquire().await.unwrap(); - sqlx::query( - "SET buzz.community_artifact_contract_ready='all-backends-enforce-community-audience'", - ) - .execute(&mut *connection) - .await - .unwrap(); - sqlx::raw_sql(include_str!( - "../../../../scripts/maintenance/community-artifact-contract.sql" - )) - .execute(&mut *connection) - .await - .unwrap(); - assert!(f.db.community_artifact_schema_ready().await.unwrap()); - } - fn principal(keys: &Keys, roster: bool) -> CommunityArtifactPrincipal { - CommunityArtifactPrincipal { - owner_admission: true, - pubkey: keys.public_key().to_bytes().to_vec(), - verified_owner: None, - require_membership: roster, - reject_required_nip_fi: false, - } - } - fn revision(f: &Fixture, d: Uuid, op: &str, prev: Option<&Event>, keys: &Keys) -> Event { - let mut tags = vec![ - vec!["ar".into(), "1".into()], - vec!["d".into(), d.to_string()], - vec!["community".into(), f.community.to_string()], - vec!["type".into(), "example.settings".into()], - vec!["op".into(), op.into()], - ]; - if op != "delete" { - tags.push(vec!["title".into(), "Settings".into()]); - } - if let Some(prev) = prev { - tags.push(vec!["prev".into(), prev.id.to_hex()]); - } - EventBuilder::new( - Kind::Custom(45010), - if op == "delete" { - "" - } else { - "community private needle" - }, - ) - .tags(tags.into_iter().map(|t| Tag::parse(t).unwrap())) - .sign_with_keys(keys) - .unwrap() - } - fn policy(f: &Fixture, ty: &str, value: &str, prev: Option<&Event>) -> Event { - EventBuilder::new(Kind::Custom(9034), "") - .tags([ - Tag::parse(["community", &f.community.to_string()]).unwrap(), - Tag::parse(["type", ty]).unwrap(), - Tag::parse(["policy", value]).unwrap(), - Tag::parse([ - "prev", - &prev.map(|e| e.id.to_hex()).unwrap_or_else(|| "0".into()), - ]) - .unwrap(), - ]) - .sign_with_keys(&f.owner) - .unwrap() - } - async fn set_policy(f: &Fixture, event: &Event) -> PolicyOutcome { - let mut tx = f.db.pool.begin().await.unwrap(); - let out = set_policy_in_transaction( - &mut tx, - f.community, - &principal(&f.owner, false), - event, - &artifact::parse_policy_command(event).unwrap(), - ) - .await - .unwrap(); - tx.commit().await.unwrap(); - out - } - async fn role(f: &Fixture, keys: &Keys, value: &str) { - sqlx::query("INSERT INTO relay_members(community_id,pubkey,role) VALUES($1,$2,$3) ON CONFLICT(community_id,pubkey) DO UPDATE SET role=EXCLUDED.role") - .bind(f.community.as_uuid()).bind(keys.public_key().to_hex()).bind(value).execute(&f.db.pool).await.unwrap(); - } - async fn accept( - f: &Fixture, - event: &Event, - reader: &CommunityArtifactPrincipal, - ) -> crate::Result { - f.db.accept_community_artifact( - f.community, - reader, - event, - &artifact::validate(event).unwrap(), - ) - .await - } - async fn read( - f: &Fixture, - reader: &CommunityArtifactPrincipal, - view: &str, - d: Uuid, - ) -> crate::Result> { - f.db.query_community_artifacts( - f.community, - reader, - &artifact::parse_query(&json!({"artifact":view,"scope":"community","#d":[d]})).unwrap(), - ) - .await - } - - /// Mutation: dropping the old primary key in expand makes the legacy - /// ON CONFLICT below fail. Mutation: omitting scope from a head/history - /// predicate aliases the legal identical d after the operator contract. - #[tokio::test] - #[ignore = "requires Postgres"] - async fn migration_schema_expand_keeps_legacy_conflict_target_contract_separates_scopes() { - let f = Fixture::new().await; - let d = Uuid::new_v4(); - let channel = f.revision(d, "create", f.a, None, &f.owner, vec![]); - assert!(matches!( - f.accept(&channel, None).await, - ArtifactOutcome::Accepted(_) - )); - // Exercise the documented pre-expansion/concurrent-prebuild procedure - // on populated tables, including recovery from rolled-back columns. - sqlx::raw_sql("ALTER TABLE artifact_heads DROP COLUMN scope; ALTER TABLE artifact_heads ALTER COLUMN channel_id SET NOT NULL; ALTER TABLE artifact_revisions DROP COLUMN scope, DROP COLUMN community_event, DROP COLUMN redacted; ALTER TABLE communities DROP COLUMN artifact_type_policies;") - .execute(&f.db.pool).await.unwrap(); - let expand = include_str!("../../../../migrations/0097_community_artifact_expand.sql"); - let additive = expand.split("-- Small deployments").next().unwrap(); - let mut tx = f.db.pool.begin().await.unwrap(); - sqlx::raw_sql(additive).execute(&mut *tx).await.unwrap(); - tx.commit().await.unwrap(); - for sql in [ - "CREATE UNIQUE INDEX CONCURRENTLY artifact_heads_scoped_identity ON artifact_heads(community_id,scope,artifact_id)", - "CREATE INDEX CONCURRENTLY artifact_revisions_scoped_identity ON artifact_revisions(community_id,scope,artifact_id)", - "CREATE INDEX CONCURRENTLY artifact_heads_live_type ON artifact_heads(community_id,scope,artifact_type,artifact_id) WHERE NOT deleted", - ] { sqlx::query(sql).execute(&f.db.pool).await.unwrap(); } - let mut tx = f.db.pool.begin().await.unwrap(); - sqlx::raw_sql(expand).execute(&mut *tx).await.unwrap(); - tx.commit().await.unwrap(); - // The exact legacy upsert target and output columns still work on the - // expanded catalog, even on a populated table. - let output:(Vec,Uuid)=sqlx::query_as("INSERT INTO artifact_heads(community_id,artifact_id,event_id,channel_id,artifact_type) VALUES($1,$2,$3,$4,'buzz.task') ON CONFLICT(community_id,artifact_id) DO UPDATE SET event_id=EXCLUDED.event_id RETURNING event_id,channel_id") - .bind(f.community.as_uuid()).bind(d).bind(channel.id.as_bytes().as_slice()).bind(f.a).fetch_one(&f.db.pool).await.unwrap(); - assert_eq!(output, (channel.id.as_bytes().to_vec(), f.a)); - assert!(!f.db.community_artifact_schema_ready().await.unwrap()); - let mut conn = f.db.pool.acquire().await.unwrap(); - assert!(sqlx::raw_sql(include_str!( - "../../../../scripts/maintenance/community-artifact-contract.sql" - )) - .execute(&mut *conn) - .await - .is_err()); - sqlx::query("ROLLBACK").execute(&mut *conn).await.unwrap(); - drop(conn); - contract(&f).await; - let community = revision(&f, d, "create", None, &f.owner); - let reader = principal(&f.owner, false); - assert!(matches!( - accept(&f, &community, &reader).await.unwrap(), - ArtifactOutcome::Accepted(_) - )); - contract(&f).await; - let channel_update = f.revision(d, "update", f.a, Some(&channel), &f.owner, vec![]); - assert!(matches!( - f.accept(&channel_update, None).await, - ArtifactOutcome::Accepted(_) - )); - assert_eq!( - read(&f, &reader, "head", d).await.unwrap()[0].event.id, - community.id - ); - assert_eq!(read(&f, &reader, "history", d).await.unwrap().len(), 1); - let (legacy, _) = f - .query(&f.owner, json!({"artifact":"history","#d":[d]}), false) - .await; - assert_eq!(legacy.len(), 2); - assert!(legacy.iter().all(|e| e.channel_id == Some(f.a))); - let deleted = revision(&f, d, "delete", Some(&community), &f.owner); - assert!(matches!( - accept(&f, &deleted, &reader).await.unwrap(), - ArtifactOutcome::Accepted(_) - )); - assert!(read(&f, &reader, "current", d).await.unwrap().is_empty()); - assert_eq!( - read(&f, &reader, "head", d).await.unwrap()[0].event.id, - deleted.id - ); - let restore = revision(&f, d, "restore", Some(&deleted), &f.owner); - assert!(matches!( - accept(&f, &restore, &reader).await.unwrap(), - ArtifactOutcome::Accepted(_) - )); - role(&f, &f.owner, "owner").await; - assert!(f - .db - .redact_community_artifact(f.community, &reader, restore.id.as_bytes()) - .await - .unwrap() - .is_some()); - assert!(read(&f, &reader, "head", d).await.unwrap().is_empty()); - assert!(f - .db - .community_artifact_accepted(f.community, &reader, &restore) - .await - .unwrap()); - assert_eq!( - f.count(&f.owner, json!({"artifact":"current","#d":[d]})) - .await, - 1 - ); - f.db.validate_deletion_serving_catalog().await.unwrap(); - } - - #[tokio::test] - #[ignore = "requires Postgres"] - async fn policy_cas_race_replay_cap_and_retained_everyone() { - let f = Fixture::new().await; - contract(&f).await; - role(&f, &f.owner, "owner").await; - let reader = principal(&f.owner, false); - let unset = - f.db.community_artifact_policy(f.community, &reader, "example.settings") - .await - .unwrap(); - assert_eq!(unset.policy, "everyone"); - assert_eq!(unset.revision, None); - let a = policy(&f, "example.settings", "admins", None); - let b = policy(&f, "example.settings", "everyone", None); - let (ra, rb) = tokio::join!(set_policy(&f, &a), set_policy(&f, &b)); - let winner = match (ra, rb) { - (PolicyOutcome::Applied, PolicyOutcome::Conflict(_)) => &a, - (PolicyOutcome::Conflict(_), PolicyOutcome::Applied) => &b, - x => panic!("one winner: {x:?}"), - }; - assert_eq!(set_policy(&f, winner).await, PolicyOutcome::Duplicate); - let everyone = policy(&f, "example.settings", "everyone", Some(winner)); - assert_eq!(set_policy(&f, &everyone).await, PolicyOutcome::Applied); - assert!(matches!( - set_policy(&f, winner).await, - PolicyOutcome::Conflict(_) - )); - let state = - f.db.community_artifact_policy(f.community, &reader, "example.settings") - .await - .unwrap(); - assert_eq!(state.policy, "everyone"); - assert_eq!(state.revision, Some(everyone.id.to_hex())); - // Fill the bounded map efficiently, then exercise the production CAS - // for both an existing slot and a new explicit everyone slot. - let entries: serde_json::Map = (0..255) - .map(|i| { - ( - format!("example.slot{i}"), - json!({"policy":"admins","revision":"a".repeat(64)}), - ) - }) - .chain(std::iter::once(( - "example.settings".into(), - json!({"policy":"everyone","revision":everyone.id.to_hex()}), - ))) - .collect(); - sqlx::query("UPDATE communities SET artifact_type_policies=$2 WHERE id=$1") - .bind(f.community.as_uuid()) - .bind(serde_json::Value::Object(entries)) - .execute(&f.db.pool) - .await - .unwrap(); - assert!(matches!( - set_policy(&f, &policy(&f, "example.new", "everyone", None)).await, - PolicyOutcome::Conflict(_) - )); - let update = policy(&f, "example.settings", "admins", Some(&everyone)); - assert_eq!(set_policy(&f, &update).await, PolicyOutcome::Applied); - let event = revision(&f, Uuid::new_v4(), "create", None, &f.peer); - assert!(accept(&f, &event, &principal(&f.peer, false)) - .await - .is_err()); - let mut delegated = principal(&f.peer, true); - delegated.verified_owner = Some(reader.pubkey.clone()); - // Delegation gives admission, never the admin edit role. - assert!(accept(&f, &event, &delegated).await.is_err()); - assert!(f - .db - .community_artifact_policy(f.community, &delegated, "example.settings") - .await - .is_ok()); - } - - #[tokio::test] - #[ignore = "requires Postgres"] - async fn policy_transaction_rechecks_timeout_before_writes_and_replays() { - let f = Fixture::new().await; - contract(&f).await; - role(&f, &f.owner, "owner").await; - let current = policy(&f, "example.settings", "admins", None); - assert_eq!(set_policy(&f, ¤t).await, PolicyOutcome::Applied); - sqlx::query("INSERT INTO community_bans(community_id,pubkey,actor_pubkey,muted_until) VALUES($1,$2,$2,now()+interval '1 hour')") - .bind(f.community.as_uuid()) - .bind(f.owner.public_key().as_bytes().as_slice()) - .execute(&f.db.pool) - .await - .unwrap(); - let next = policy(&f, "example.settings", "everyone", Some(¤t)); - for event in [¤t, &next] { - let command = buzz_core::artifact::parse_policy_command(event).unwrap(); - let mut tx = f.db.pool.begin().await.unwrap(); - let result = set_policy_in_transaction( - &mut tx, - f.community, - &principal(&f.owner, false), - event, - &command, - ) - .await; - assert!( - matches!(result, Err(crate::DbError::AccessDenied(_))), - "{result:?}" - ); - tx.rollback().await.unwrap(); - } - } - - /// Admission must be authoritative even with a caller holding stale - /// transport ownership/membership. Accepted replay ignores timeout and - /// policy, but never tenant or ban state. - #[tokio::test] - #[ignore = "requires Postgres"] - async fn replay_and_reads_recheck_admission_and_applicable_owner() { - let f = Fixture::new().await; - contract(&f).await; - role(&f, &f.owner, "owner").await; - let reader = principal(&f.peer, false); - let d = Uuid::new_v4(); - let event = revision(&f, d, "create", None, &f.peer); - assert!(matches!( - accept(&f, &event, &reader).await.unwrap(), - ArtifactOutcome::Accepted(_) - )); - let command = policy(&f, "example.settings", "admins", None); - assert_eq!(set_policy(&f, &command).await, PolicyOutcome::Applied); - sqlx::query("INSERT INTO community_bans(community_id,pubkey,actor_pubkey,muted_until) VALUES($1,$2,$3,now()+interval '1 hour')") - .bind(f.community.as_uuid()).bind(&reader.pubkey).bind(f.owner.public_key().as_bytes().as_slice()).execute(&f.db.pool).await.unwrap(); - assert!(f - .db - .community_artifact_accepted(f.community, &reader, &event) - .await - .unwrap()); - assert_eq!(read(&f, &reader, "current", d).await.unwrap().len(), 1); - let mut roster = reader.clone(); - roster.require_membership = true; - assert!(read(&f, &roster, "current", d).await.is_err()); - role(&f, &f.peer, "member").await; - assert_eq!(read(&f, &roster, "current", d).await.unwrap().len(), 1); - sqlx::query("DELETE FROM relay_members WHERE community_id=$1 AND pubkey=$2") - .bind(f.community.as_uuid()) - .bind(f.peer.public_key().to_hex()) - .execute(&f.db.pool) - .await - .unwrap(); - assert!(read(&f, &roster, "current", d).await.is_err()); - roster.verified_owner = Some(f.owner.public_key().to_bytes().to_vec()); - assert_eq!(read(&f, &roster, "current", d).await.unwrap().len(), 1); - sqlx::query("INSERT INTO community_bans(community_id,pubkey,actor_pubkey,banned) VALUES($1,$2,$2,true)") - .bind(f.community.as_uuid()).bind(f.owner.public_key().as_bytes().as_slice()).execute(&f.db.pool).await.unwrap(); - assert!(read(&f, &roster, "current", d).await.is_err()); - sqlx::query("UPDATE community_bans SET banned=true WHERE community_id=$1") - .bind(f.community.as_uuid()) - .execute(&f.db.pool) - .await - .unwrap(); - assert!(f - .db - .community_artifact_accepted(f.community, &reader, &event) - .await - .is_err()); - let wrong = CommunityId::from_uuid(Uuid::new_v4()); - assert!(f - .db - .community_artifact_accepted(wrong, &reader, &event) - .await - .is_err()); - } - - #[tokio::test] - #[ignore = "requires Postgres"] - async fn community_snapshot_capacity_and_new_reads_use_current_admission() { - let f = Fixture::new().await; - let small = Db::from_pool( - sqlx::postgres::PgPoolOptions::new() - .max_connections(2) - .connect(&crate::test_support::database_url()) - .await - .unwrap(), - ); - let open = principal(&f.peer, false); - let snapshot = small - .open_community_artifact_snapshot(f.community, &open) - .await - .unwrap(); - assert!(matches!( - small - .open_community_artifact_snapshot(f.community, &open) - .await, - Err(DbError::ArtifactSyncLimit) - )); - small - .community_artifact_policy(f.community, &open, "example.settings") - .await - .unwrap(); - snapshot.finish().await.unwrap(); - - role(&f, &f.peer, "member").await; - let reader = principal(&f.peer, true); - let snapshot = - f.db.open_community_artifact_snapshot(f.community, &reader) - .await - .unwrap(); - snapshot.finish().await.unwrap(); - sqlx::query("DELETE FROM relay_members WHERE community_id=$1 AND pubkey=$2") - .bind(f.community.as_uuid()) - .bind(f.peer.public_key().to_hex()) - .execute(&f.db.pool) - .await - .unwrap(); - assert!(matches!( - f.db.open_community_artifact_snapshot(f.community, &reader) - .await, - Err(DbError::AccessDenied(_)) - )); - - role(&f, &f.owner, "owner").await; - sqlx::query("UPDATE communities SET archived_at=clock_timestamp() WHERE id=$1") - .bind(f.community.as_uuid()) - .execute(&f.db.pool) - .await - .unwrap(); - let open_reader = principal(&f.peer, false); - assert!(matches!( - f.db.open_community_artifact_snapshot(f.community, &open_reader) - .await, - Err(DbError::AccessDenied(_)) - )); - let event = revision(&f, Uuid::new_v4(), "create", None, &f.peer); - assert!(accept(&f, &event, &open_reader).await.is_err()); - let command = policy(&f, "example.settings", "admins", None); - let parsed = buzz_core::artifact::parse_policy_command(&command).unwrap(); - let mut tx = f.db.pool.begin().await.unwrap(); - assert!(set_policy_in_transaction( - &mut tx, - f.community, - &principal(&f.owner, false), - &command, - &parsed - ) - .await - .is_err()); - } - #[tokio::test] - #[ignore = "requires Postgres"] - async fn cluster_global_community_artifact_snapshot_can_open_during_ownership_transfer() { - use crate::relay_members::{transfer_ownership, TransferResult}; - use crate::test_support::{named_pool, wait_for_lock_wait}; - - let f = Fixture::new().await; - role(&f, &f.owner, "owner").await; - role(&f, &f.peer, "member").await; - - // Pause the transfer after it takes the community row and before it - // promotes the transferee. The reader can still take the committed cut. - let mut blocker = f.db.pool.begin().await.unwrap(); - let owner = f.owner.public_key().to_hex(); - sqlx::query("SELECT 1 FROM relay_members WHERE community_id=$1 AND pubkey=$2 FOR UPDATE") - .bind(f.community.as_uuid()) - .bind(&owner) - .fetch_one(&mut *blocker) - .await - .unwrap(); - - let transfer_name = format!("artifact-transfer-{}", Uuid::new_v4().simple()); - let transfer_pool = named_pool(&transfer_name).await; - let community = f.community; - let peer = f.peer.public_key().to_hex(); - let relay = f.relay.clone(); - let transfer = tokio::spawn(async move { - transfer_ownership(&transfer_pool, community, &peer, &owner, &relay).await - }); - wait_for_lock_wait(&f.db.pool, &transfer_name).await; - - let reader = principal(&f.peer, true); - let snapshot = tokio::time::timeout( - std::time::Duration::from_secs(1), - f.db.open_community_artifact_snapshot(community, &reader), - ) - .await - .expect("snapshot admission must not wait for the transfer") - .unwrap(); - snapshot.finish().await.unwrap(); - blocker.rollback().await.unwrap(); - - let result = transfer - .await - .unwrap() - .expect("ownership transfer succeeds"); - assert!(matches!(result.outcome, TransferResult::Transferred { .. })); - } - - #[tokio::test] - #[ignore = "requires Postgres"] - async fn direct_artifact_write_does_not_wait_for_delegated_roster_row() { - let f = Fixture::new().await; - contract(&f).await; - role(&f, &f.owner, "owner").await; - role(&f, &f.peer, "member").await; - let mut member = principal(&f.peer, true); - member.verified_owner = Some(f.owner.public_key().to_bytes().to_vec()); - member.owner_admission = true; - - let mut roster_edit = f.db.pool.begin().await.unwrap(); - sqlx::query("SELECT 1 FROM relay_members WHERE community_id=$1 AND pubkey=$2 FOR UPDATE") - .bind(f.community.as_uuid()) - .bind(f.owner.public_key().to_hex()) - .fetch_one(&mut *roster_edit) - .await - .unwrap(); - let event = revision(&f, Uuid::new_v4(), "create", None, &f.peer); - let result = tokio::time::timeout( - std::time::Duration::from_secs(1), - accept(&f, &event, &member), - ) - .await - .expect("a direct member write does not depend on the owner's roster lock"); - assert!(matches!(result, Ok(ArtifactOutcome::Accepted(_)))); - roster_edit.rollback().await.unwrap(); - } - - /// A policy update's uncommitted state must fence new artifact admission, - /// even when that type had no previous policy row. - #[tokio::test] - #[ignore = "requires Postgres"] - async fn cluster_global_member_write_waits_for_admins_policy_commit() { - let f = Fixture::new().await; - contract(&f).await; - role(&f, &f.owner, "owner").await; - role(&f, &f.peer, "member").await; - let command = policy(&f, "example.settings", "admins", None); - let parsed = buzz_core::artifact::parse_policy_command(&command).unwrap(); - let mut tx = f.db.pool.begin().await.unwrap(); - assert_eq!( - set_policy_in_transaction( - &mut tx, - f.community, - &principal(&f.owner, false), - &command, - &parsed - ) - .await - .unwrap(), - PolicyOutcome::Applied - ); - let event = revision(&f, Uuid::new_v4(), "create", None, &f.peer); - let env = buzz_core::artifact::validate(&event).unwrap(); - let writer_name = format!("artifact-policy-writer-{}", Uuid::new_v4().simple()); - let db = Db::from_pool(crate::test_support::named_pool(&writer_name).await); - let community = f.community; - let peer = principal(&f.peer, true); - let pending = tokio::spawn(async move { - db.accept_community_artifact(community, &peer, &event, &env) - .await - }); - crate::test_support::wait_for_lock_wait(&f.db.pool, &writer_name).await; - tx.commit().await.unwrap(); - assert!( - matches!(pending.await.unwrap(), Err(DbError::AccessDenied(_))), - "committed admins policy must reject member write" - ); - } -} diff --git a/crates/buzz-db/src/store/artifact_query.rs b/crates/buzz-db/src/store/artifact_query.rs index 429197a9870..9a5cee1bc4f 100644 --- a/crates/buzz-db/src/store/artifact_query.rs +++ b/crates/buzz-db/src/store/artifact_query.rs @@ -21,12 +21,12 @@ pub(super) fn predicates( ) { match query.view { ArtifactView::Current => { - qb.push("JOIN artifact_heads a ON a.community_id=e.community_id AND a.event_id=e.id AND a.scope='channel' AND NOT a.deleted "); + qb.push("JOIN artifact_heads a ON a.community_id=e.community_id AND a.event_id=e.id AND NOT a.deleted "); } ArtifactView::Head => { - qb.push("JOIN artifact_heads a ON a.community_id=e.community_id AND a.event_id=e.id AND a.scope='channel' "); + qb.push("JOIN artifact_heads a ON a.community_id=e.community_id AND a.event_id=e.id "); } - ArtifactView::History | ArtifactView::Policy => {} + ArtifactView::History => {} } push_scope( qb, @@ -62,9 +62,7 @@ fn push_scope( ) { // The explicit kind lets the community/kind index exclude chat before // the join, even for an unfiltered current-state page. - qb.push("WHERE e.community_id=").push_bind(community.as_uuid()).push(" AND e.kind=45010 AND NOT ") - .push(crate::community_artifact_tag_sql!("e.tags")) - .push(" AND e.deleted_at IS NULL AND EXISTS (SELECT 1 FROM channels c WHERE c.community_id=e.community_id AND c.id=e.channel_id AND c.deleted_at IS NULL AND (") + qb.push("WHERE e.community_id=").push_bind(community.as_uuid()).push(" AND e.kind=45010 AND e.deleted_at IS NULL AND EXISTS (SELECT 1 FROM channels c WHERE c.community_id=e.community_id AND c.id=e.channel_id AND c.deleted_at IS NULL AND (") .push(crate::store::channel::legacy_channel_type_sql("c.channel_type")) .push(" OR c.id=ANY(") .push_bind(named_channels.clone()) @@ -134,67 +132,19 @@ pub enum SnapshotDenied { Restricted, } -pub(super) async fn begin_snapshot( - connection: PoolConnection, -) -> Result> { - let mut tx = Transaction::begin(connection, None).await?; - sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY") - .execute(&mut *tx) - .await?; - sqlx::query("SET LOCAL statement_timeout='2s'") - .execute(&mut *tx) - .await?; - Ok(tx) -} - -enum SnapshotAudience { - Channels { - reader: Vec, - channels: Vec, - }, - Community { - _permit: tokio::sync::OwnedSemaphorePermit, - }, -} - /// One read-only `REPEATABLE READ` snapshot of a sync's current heads, read /// in keyset pages ordered by artifact identity. Every page sees the same /// database snapshot, so the pages together are one consistent cut. pub struct ArtifactSnapshot { tx: Transaction<'static, Postgres>, community: CommunityId, - audience: SnapshotAudience, + reader: Vec, + channels: Vec, after: Option, done: bool, } impl ArtifactSnapshot { - fn new( - tx: Transaction<'static, Postgres>, - community: CommunityId, - audience: SnapshotAudience, - ) -> Self { - Self { - tx, - community, - audience, - after: None, - done: false, - } - } - - pub(super) fn for_community( - tx: Transaction<'static, Postgres>, - community: CommunityId, - permit: tokio::sync::OwnedSemaphorePermit, - ) -> Self { - Self::new( - tx, - community, - SnapshotAudience::Community { _permit: permit }, - ) - } - /// Read the next page of at most `page` heads that match `tags`, ordered /// by `d`. Returns an empty page once the set is exhausted. pub async fn next_page( @@ -205,21 +155,17 @@ impl ArtifactSnapshot { if self.done { return Ok(vec![]); } - let mut qb = match &self.audience { - SnapshotAudience::Channels { reader, channels } => { - let mut qb = QueryBuilder::::new( - "SELECT e.id,e.pubkey,e.created_at,e.kind,e.tags,e.content,e.sig,e.received_at,e.channel_id,a.artifact_id FROM events e ", - ); - qb.push("JOIN artifact_heads a ON a.community_id=e.community_id AND a.event_id=e.id AND a.scope='channel' AND NOT a.deleted "); - push_scope(&mut qb, self.community, reader, tags, channels.clone()); - qb - } - SnapshotAudience::Community { .. } => super::community_artifact::query_builder( - self.community, - ArtifactView::Current, - tags, - ), - }; + let mut qb = QueryBuilder::::new( + "SELECT e.id,e.pubkey,e.created_at,e.kind,e.tags,e.content,e.sig,e.received_at,e.channel_id,a.artifact_id FROM events e ", + ); + qb.push("JOIN artifact_heads a ON a.community_id=e.community_id AND a.event_id=e.id AND NOT a.deleted "); + push_scope( + &mut qb, + self.community, + &self.reader, + tags, + self.channels.clone(), + ); if let Some(after) = self.after { qb.push(" AND a.artifact_id>").push_bind(after); } @@ -229,10 +175,7 @@ impl ArtifactSnapshot { if let Some(last) = rows.last() { self.after = Some(sqlx::Row::try_get(last, "artifact_id")?); } - match &self.audience { - SnapshotAudience::Channels { .. } => rows_to_events(rows), - SnapshotAudience::Community { .. } => super::community_artifact::rows_to_events(rows), - } + rows_to_events(rows) } /// End the snapshot. Dropping it rolls the read-only transaction back. @@ -253,13 +196,6 @@ impl Db { query: &ArtifactQuery, count: bool, ) -> Result<(Vec, i64)> { - if query.scope != buzz_core::artifact::ArtifactScope::Channel - || query.view == ArtifactView::Policy - { - return Err(crate::DbError::AccessDenied( - "explicit community admission required".into(), - )); - } let connection = read_connection(self).await?; let mut tx = sqlx::Transaction::begin(connection, None).await?; sqlx::query("SET LOCAL statement_timeout='2s'") @@ -299,7 +235,7 @@ impl Db { let mut qb = QueryBuilder::::new( "SELECT e.id,e.pubkey,e.created_at,e.kind,e.tags,e.content,e.sig,e.received_at,e.channel_id,a.deleted FROM events e ", ); - qb.push("JOIN artifact_heads a ON a.community_id=e.community_id AND a.event_id=e.id AND a.scope='channel' AND a.artifact_id=") + qb.push("JOIN artifact_heads a ON a.community_id=e.community_id AND a.event_id=e.id AND a.artifact_id=") .push_bind(artifact) .push(" "); push_scope(&mut qb, community, reader, &[], named_channels.to_vec()); @@ -322,7 +258,14 @@ impl Db { reader: &[u8], channels: &[Uuid], ) -> Result> { - let mut tx = begin_snapshot(read_connection(self).await?).await?; + let connection = read_connection(self).await?; + let mut tx = sqlx::Transaction::begin(connection, None).await?; + sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY") + .execute(&mut *tx) + .await?; + sqlx::query("SET LOCAL statement_timeout='2s'") + .execute(&mut *tx) + .await?; let readable: i64 = sqlx::query_scalar( "SELECT count(*) FROM channels c WHERE c.community_id=$1 AND c.id=ANY($2) AND c.deleted_at IS NULL AND (c.visibility='open' OR EXISTS (SELECT 1 FROM channel_members m WHERE m.community_id=c.community_id AND m.channel_id=c.id AND m.pubkey=$3 AND m.removed_at IS NULL))", ) @@ -334,13 +277,13 @@ impl Db { if readable != channels.len() as i64 { return Ok(Err(SnapshotDenied::Restricted)); } - Ok(Ok(ArtifactSnapshot::new( + Ok(Ok(ArtifactSnapshot { tx, community, - SnapshotAudience::Channels { - reader: reader.to_vec(), - channels: channels.to_vec(), - }, - ))) + reader: reader.to_vec(), + channels: channels.to_vec(), + after: None, + done: false, + })) } } diff --git a/crates/buzz-db/src/store/artifact_sync.rs b/crates/buzz-db/src/store/artifact_sync.rs index f802024a406..4da01728fd0 100644 --- a/crates/buzz-db/src/store/artifact_sync.rs +++ b/crates/buzz-db/src/store/artifact_sync.rs @@ -175,7 +175,7 @@ WITH readable AS NOT MATERIALIZED ( SELECT a.modified_at AS at,1 AS source,a.artifact_id::text AS id, a.artifact_id,NULL::uuid AS removed_channel FROM artifact_heads a - WHERE a.community_id=$1 AND a.scope='channel' AND a.modified_at >= COALESCE($3::timestamptz,'epoch'::timestamptz) + WHERE a.community_id=$1 AND a.modified_at >= COALESCE($3::timestamptz,'epoch'::timestamptz) AND a.modified_at <= $4 AND a.channel_id IN (SELECT id FROM readable) AND ($3::timestamptz IS NOT NULL OR NOT a.deleted) AND (cardinality($8::text[])=0 OR a.artifact_type=ANY($8)) @@ -189,14 +189,14 @@ WITH readable AS NOT MATERIALIZED ( UNION ALL SELECT m.sync_modified_at,2,a.artifact_id::text,a.artifact_id,NULL::uuid FROM channel_members m JOIN artifact_heads a - ON a.scope='channel' AND a.community_id=m.community_id AND a.channel_id=m.channel_id + ON a.community_id=m.community_id AND a.channel_id=m.channel_id WHERE m.community_id=$1 AND m.pubkey=$2 AND m.removed_at IS NULL AND $3::timestamptz IS NOT NULL AND m.sync_modified_at >= $3 AND m.sync_modified_at <= $4 AND a.channel_id IN (SELECT id FROM readable) AND (cardinality($8::text[])=0 OR a.artifact_type=ANY($8)) UNION ALL SELECT DISTINCT r.modified_at,3,r.artifact_id::text,r.artifact_id,NULL::uuid - FROM artifact_revisions r WHERE r.community_id=$1 AND r.scope='channel' + FROM artifact_revisions r WHERE r.community_id=$1 AND r.source_channel_id IS NOT NULL AND r.source_channel_id IN (SELECT id FROM readable) AND $3::timestamptz IS NOT NULL AND r.modified_at >= $3 AND r.modified_at <= $4 ) diff --git a/crates/buzz-db/src/store/community_artifact.rs b/crates/buzz-db/src/store/community_artifact.rs deleted file mode 100644 index 751425ca90d..00000000000 --- a/crates/buzz-db/src/store/community_artifact.rs +++ /dev/null @@ -1,659 +0,0 @@ -//! Explicit NIP-AR community audience. Payloads live in the revision ledger, -//! outside the event store, search index, mentions and conversation side effects. -use super::artifact::{artifact_receipt_exists, check_artifact_head, ArtifactOutcome}; -use crate::{ArtifactSnapshot, Db, DbError, Result}; -use buzz_core::artifact::{ - canonical_uuid, ArtifactEnvelope, ArtifactOp, ArtifactQuery, ArtifactScope, - ArtifactTypePolicyCommand, ArtifactView, MAX_COMMUNITY_POLICIES, -}; -use buzz_core::{CommunityId, StoredEvent}; -use nostr::Event; -use serde_json::{json, Value}; -use sqlx::{PgConnection, Postgres, QueryBuilder, Row, Transaction}; -use uuid::Uuid; - -/// Transport-proven principal; never constructed from artifact content. -#[derive(Clone, Debug)] -pub struct CommunityArtifactPrincipal { - /// Authenticated event signer or reader. - pub pubkey: Vec, - /// Owner proven by the current authenticated transport, if delegated. - pub verified_owner: Option>, - /// Current transport policy permits owner roster fallback. The verified - /// owner remains a restriction identity even when this is false. - pub owner_admission: bool, - /// Current effective relay admission mode. - pub require_membership: bool, - /// A long-lived socket without FI evidence may read only while the tenant - /// policy permits it. HTTP requests use their own policy admission. - pub reject_required_nip_fi: bool, -} - -fn denied() -> DbError { - DbError::AccessDenied("community artifact access denied".into()) -} - -async fn set_admission_timeouts(conn: &mut PgConnection) -> Result<()> { - sqlx::raw_sql("SET LOCAL statement_timeout='2s'; SET LOCAL lock_timeout='2s'") - .execute(conn) - .await?; - Ok(()) -} - -// Match relay_invite::lock_admission and take this advisory lock before any -// row lock, so a restriction writer can commit before admission rechecks it. -async fn lock_restriction_writers(conn: &mut PgConnection, community: CommunityId) -> Result<()> { - sqlx::query( - "SELECT pg_advisory_xact_lock_shared(hashtextextended('invite-admission:' || $1::text,0))", - ) - .bind(community.as_uuid()) - .execute(conn) - .await?; - Ok(()) -} - -async fn lock_member_role( - conn: &mut PgConnection, - community: CommunityId, - pubkey: &[u8], -) -> Result> { - Ok(sqlx::query_scalar( - "SELECT role FROM relay_members WHERE community_id=$1 AND pubkey=$2 FOR SHARE", - ) - .bind(community.as_uuid()) - .bind(hex::encode(pubkey)) - .fetch_optional(conn) - .await?) -} - -/// Call with the restriction and active community locks held. Only the -/// roster row supplying admission needs a member lock. -async fn authorize_members( - conn: &mut PgConnection, - community: CommunityId, - principal: &CommunityArtifactPrincipal, - allow_owner_fallback: bool, -) -> Result { - let direct = lock_member_role(conn, community, &principal.pubkey).await?; - let delegated = if principal.require_membership - && direct.is_none() - && allow_owner_fallback - && principal.owner_admission - { - match &principal.verified_owner { - Some(owner) => lock_member_role(conn, community, owner).await?.is_some(), - None => false, - } - } else { - false - }; - let row = sqlx::query("SELECT COALESCE(bool_or(banned AND (ban_expires_at IS NULL OR ban_expires_at > clock_timestamp())),false) AS banned, COALESCE(bool_or(muted_until > clock_timestamp()),false) AS timed_out FROM community_bans WHERE community_id=$1 AND pubkey IN (SELECT $2::bytea UNION ALL SELECT $3::bytea UNION ALL SELECT agent_owner_pubkey FROM users WHERE community_id=$1 AND pubkey=$2)") - .bind(community.as_uuid()).bind(&principal.pubkey).bind(&principal.verified_owner).fetch_one(&mut *conn).await?; - if row.try_get::("banned")? - || (principal.require_membership && direct.is_none() && !delegated) - { - return Err(denied()); - } - Ok(Authority { - admin: matches!(direct.as_deref(), Some("owner" | "admin")), - timed_out: row.try_get("timed_out")?, - }) -} -struct Authority { - admin: bool, - timed_out: bool, -} - -// Take the community row before member rows, matching ownership transfer. -// SHARE conflicts with archive/auth-policy writers' NO KEY UPDATE lock while -// allowing readers together. Policy commands take NO KEY UPDATE up front. -async fn lock_active_community(conn: &mut PgConnection, community: CommunityId) -> Result { - sqlx::query_scalar("SELECT requires_nip_fi FROM communities WHERE id=$1 AND archived_at IS NULL AND deleted_at IS NULL AND deletion_state='active' FOR SHARE") - .bind(community.as_uuid()) - .fetch_optional(conn) - .await? - .ok_or_else(denied) -} - -/// Policy lookup result. Explicit `everyone` entries keep their revision and slot. -#[derive(Debug, serde::Serialize, PartialEq, Eq)] -pub struct ArtifactTypePolicy { - /// Effective write policy. - pub policy: String, - /// Last accepted command ID, absent only when never configured. - pub revision: Option, -} -fn policy_value(state: &Value, artifact_type: &str) -> Result { - match state.get(artifact_type) { - None => Ok(ArtifactTypePolicy { - policy: "everyone".into(), - revision: None, - }), - Some(value) => Ok(ArtifactTypePolicy { - policy: value - .get("policy") - .and_then(Value::as_str) - .filter(|p| matches!(*p, "everyone" | "admins")) - .ok_or_else(|| DbError::InvalidData("invalid stored artifact policy".into()))? - .into(), - revision: Some( - value - .get("revision") - .and_then(Value::as_str) - .ok_or_else(|| { - DbError::InvalidData("invalid stored artifact policy revision".into()) - })? - .into(), - ), - }), - } -} - -/// Result of a policy CAS. Its caller commits the audit on the same transaction. -#[derive(Debug, PartialEq, Eq)] -pub enum PolicyOutcome { - /// A new accepted command; append its audit entry before committing. - Applied, - /// Exact current command retry, with current direct authority. - Duplicate, - /// Stale `prev` or the bounded policy map is full. - Conflict(&'static str), -} - -/// Validate and apply a policy CAS inside the caller's audit transaction. -/// Community deletion admission and current direct authority are rechecked here. -/// The caller must have verified transport, signature, tenant and `admin:users`. -pub async fn set_policy_in_transaction( - tx: &mut Transaction<'static, Postgres>, - community: CommunityId, - principal: &CommunityArtifactPrincipal, - event: &Event, - command: &ArtifactTypePolicyCommand, -) -> Result { - if command.community != *community.as_uuid() - || event.pubkey.as_bytes().as_slice() != principal.pubkey - { - return Err(denied()); - } - set_admission_timeouts(tx).await?; - crate::deletion::guard_community_write(tx, community).await?; - lock_restriction_writers(tx, community).await?; - // The row lock fences artifact writers' SHARE locks and permits foreign-key - // checks by membership writers. It also serializes policy map updates. - let state: Value = - sqlx::query_scalar("SELECT artifact_type_policies FROM communities WHERE id=$1 AND archived_at IS NULL AND deleted_at IS NULL AND deletion_state='active' FOR NO KEY UPDATE") - .bind(community.as_uuid()) - .fetch_optional(&mut **tx) - .await? - .ok_or_else(denied)?; - let authority = authorize_members(tx, community, principal, false).await?; - // Recheck the shared relay-admin write restriction under admission locks - // before accepting either a new policy or an exact retry. - if !authority.admin || authority.timed_out { - return Err(denied()); - } - let current = policy_value(&state, &command.artifact_type)?; - // An authorized retry of the current command bypasses the freshness check. - if current.revision.as_deref() == Some(event.id.to_hex().as_str()) { - return Ok(PolicyOutcome::Duplicate); - } - let now = chrono::Utc::now().timestamp(); - if event.created_at.as_secs().abs_diff(now as u64) > 120 { - return Err(DbError::InvalidData( - "policy command timestamp out of range".into(), - )); - } - if command.prev != current.revision { - return Ok(PolicyOutcome::Conflict("artifact policy changed")); - } - let mut entries = state - .as_object() - .cloned() - .ok_or_else(|| DbError::InvalidData("invalid artifact policy state".into()))?; - if !entries.contains_key(&command.artifact_type) && entries.len() >= MAX_COMMUNITY_POLICIES { - return Ok(PolicyOutcome::Conflict("artifact policy limit exceeded")); - } - entries.insert( - command.artifact_type.clone(), - json!({"policy":command.policy,"revision":event.id.to_hex()}), - ); - sqlx::query("UPDATE communities SET artifact_type_policies=$2 WHERE id=$1 AND deletion_state = 'active' AND deleted_at IS NULL") - .bind(community.as_uuid()) - .bind(Value::Object(entries)) - .execute(&mut **tx) - .await?; - Ok(PolicyOutcome::Applied) -} - -impl Db { - /// Contract readiness, checked before activation. The old unscoped key must - /// be gone and the scoped primary key valid; the expand alone never activates. - pub async fn community_artifact_schema_ready(&self) -> Result { - Ok(sqlx::query_scalar(r#" - SELECT EXISTS ( - SELECT 1 FROM pg_index i - WHERE i.indrelid='artifact_heads'::regclass AND i.indisprimary - AND i.indisvalid AND i.indisready AND i.indpred IS NULL AND i.indexprs IS NULL - AND (SELECT array_agg(a.attname::text ORDER BY k.ord) - FROM unnest(i.indkey) WITH ORDINALITY k(num,ord) - JOIN pg_attribute a ON a.attrelid=i.indrelid AND a.attnum=k.num) - = ARRAY['community_id','scope','artifact_id'] - ) AND NOT EXISTS ( - SELECT 1 FROM pg_index i WHERE i.indrelid='artifact_heads'::regclass AND i.indisunique - AND (SELECT array_agg(a.attname::text ORDER BY k.ord) - FROM unnest(i.indkey) WITH ORDINALITY k(num,ord) - JOIN pg_attribute a ON a.attrelid=i.indrelid AND a.attnum=k.num) - = ARRAY['community_id','artifact_id'] - ) AND ( - SELECT count(*)=7 FROM (VALUES - ('artifact_heads','scope','text',true), - ('artifact_heads','channel_id','uuid',false), - ('artifact_revisions','scope','text',true), - ('artifact_revisions','community_event','jsonb',false), - ('artifact_revisions','redacted','boolean',true), - ('communities','artifact_type_policies','jsonb',true), - ('artifact_revisions','event_id','bytea',true) - ) expected(rel,col,typ,required) - JOIN pg_attribute a ON a.attrelid=to_regclass(expected.rel) - AND a.attname=expected.col AND NOT a.attisdropped - AND a.atttypid=to_regtype(expected.typ) AND a.attnotnull=expected.required - ) AND ( - SELECT count(*)=2 FROM pg_attribute a JOIN pg_attrdef d - ON d.adrelid=a.attrelid AND d.adnum=a.attnum - WHERE a.attrelid IN ('artifact_heads'::regclass,'artifact_revisions'::regclass) - AND a.attname='scope' AND pg_get_expr(d.adbin,d.adrelid) = $$'channel'::text$$ - ) - "#).fetch_one(&self.pool).await?) - } - // Admission and content use the same repeatable-read cut on the writer. - async fn begin_community_artifact_read( - &self, - community: CommunityId, - principal: &CommunityArtifactPrincipal, - ) -> Result> { - let connection = crate::observability::acquire_writer_until( - &self.pool, - crate::observability::WriterOperation::SubscriptionHistory, - tokio::time::Instant::now() + std::time::Duration::from_secs(2), - ) - .await?; - let mut tx = super::artifact_query::begin_snapshot(connection).await?; - let admitted: bool = sqlx::query_scalar( - "SELECT EXISTS ( - SELECT 1 FROM communities c - WHERE c.id=$1 AND c.archived_at IS NULL AND c.deleted_at IS NULL - AND c.deletion_state='active' AND (NOT $6 OR NOT c.requires_nip_fi) - AND (NOT $4 OR EXISTS ( - SELECT 1 FROM relay_members m WHERE m.community_id=c.id - AND (m.pubkey=encode($2,'hex') OR ($5 AND m.pubkey=encode($3,'hex'))) - )) - AND NOT EXISTS ( - SELECT 1 FROM community_bans b WHERE b.community_id=c.id AND b.banned - AND (b.ban_expires_at IS NULL OR b.ban_expires_at>clock_timestamp()) - AND b.pubkey IN ( - SELECT $2::bytea UNION ALL SELECT $3::bytea - UNION ALL SELECT u.agent_owner_pubkey FROM users u - WHERE u.community_id=c.id AND u.pubkey=$2 - ) - ) - )", - ) - .bind(community.as_uuid()) - .bind(&principal.pubkey) - .bind(&principal.verified_owner) - .bind(principal.require_membership) - .bind(principal.owner_admission) - .bind(principal.reject_required_nip_fi) - .fetch_one(&mut *tx) - .await?; - if !admitted { - return Err(denied()); - } - Ok(tx) - } - /// Read policy with current admission. Unset types have no revision. - pub async fn community_artifact_policy( - &self, - community: CommunityId, - principal: &CommunityArtifactPrincipal, - artifact_type: &str, - ) -> Result { - let mut tx = self - .begin_community_artifact_read(community, principal) - .await?; - let state: Value = - sqlx::query_scalar("SELECT artifact_type_policies FROM communities WHERE id=$1") - .bind(community.as_uuid()) - .fetch_one(&mut *tx) - .await?; - let policy = policy_value(&state, artifact_type)?; - tx.commit().await?; - Ok(policy) - } - /// Exact accepted replay needs admission and tenant binding, never edit authority. - pub async fn community_artifact_accepted( - &self, - community: CommunityId, - principal: &CommunityArtifactPrincipal, - event: &Event, - ) -> Result { - let env = buzz_core::artifact::validate(event).map_err(|_| denied())?; - check_revision_binding(community, principal, event, &env)?; - let mut tx = self - .begin_community_artifact_read(community, principal) - .await?; - let accepted = - artifact_receipt_exists(&mut tx, community, event.id.as_bytes(), Some("community")) - .await?; - tx.commit().await?; - Ok(accepted) - } - /// Community CAS: admission, policy scope, identity, head check, ledger and - /// head persist. No event-store insert or conversation side effects. - pub async fn accept_community_artifact( - &self, - community: CommunityId, - principal: &CommunityArtifactPrincipal, - event: &Event, - env: &ArtifactEnvelope, - ) -> Result { - check_revision_binding(community, principal, event, env)?; - let mut tx = self.begin_event_write_transaction(community).await?; - set_admission_timeouts(tx.conn()).await?; - lock_restriction_writers(tx.conn(), community).await?; - lock_active_community(tx.conn(), community).await?; - let authority = authorize_members(tx.conn(), community, principal, true).await?; - sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))") - .bind(format!("artifact:{community}:community:{}", env.id)) - .execute(tx.conn()) - .await?; - if artifact_receipt_exists(tx.conn(), community, event.id.as_bytes(), Some("community")) - .await? - { - return Ok(ArtifactOutcome::Duplicate); - } - if authority.timed_out { - return Err(denied()); - } - let state: Value = - sqlx::query_scalar("SELECT artifact_type_policies FROM communities WHERE id=$1") - .bind(community.as_uuid()) - .fetch_one(tx.conn()) - .await?; - if policy_value(&state, &env.artifact_type)?.policy == "admins" && !authority.admin { - return Err(denied()); - } - let head=sqlx::query("SELECT event_id,artifact_type,deleted FROM artifact_heads WHERE community_id=$1 AND scope='community' AND artifact_id=$2 FOR UPDATE") - .bind(community.as_uuid()).bind(env.id).fetch_optional(tx.conn()).await?; - if let Some(outcome) = check_artifact_head(env, head.as_ref())? { - return Ok(outcome); - } - sqlx::query("INSERT INTO artifact_revisions(community_id,scope,event_id,artifact_id,community_event,modified_at) VALUES($1,'community',$2,$3,$4,clock_timestamp())") - .bind(community.as_uuid()).bind(event.id.as_bytes().as_slice()).bind(env.id).bind(serde_json::to_value(event).map_err(|e|DbError::InvalidData(e.to_string()))?).execute(tx.conn()).await?; - sqlx::query("INSERT INTO artifact_heads(community_id,scope,artifact_id,event_id,channel_id,artifact_type,deleted,modified_at) VALUES($1,'community',$2,$3,NULL,$4,$5,clock_timestamp()) ON CONFLICT(community_id,scope,artifact_id) DO UPDATE SET event_id=EXCLUDED.event_id,deleted=EXCLUDED.deleted,modified_at=clock_timestamp()") - .bind(community.as_uuid()).bind(env.id).bind(event.id.as_bytes().as_slice()).bind(&env.artifact_type).bind(env.op==ArtifactOp::Delete).execute(tx.conn()).await?; - tx.commit().await?; - Ok(ArtifactOutcome::Accepted(vec![StoredEvent::new( - event.clone(), - None, - )])) - } -} - -fn check_revision_binding( - community: CommunityId, - principal: &CommunityArtifactPrincipal, - event: &Event, - env: &ArtifactEnvelope, -) -> Result<()> { - if env.scope != ArtifactScope::Community - || env.community != Some(*community.as_uuid()) - || event.pubkey.as_bytes().as_slice() != principal.pubkey - { - return Err(denied()); - } - Ok(()) -} - -pub(super) fn query_builder( - community: CommunityId, - view: ArtifactView, - tags: &[(String, Vec)], -) -> QueryBuilder { - let mut qb = QueryBuilder::new("SELECT r.artifact_id,r.community_event,r.modified_at "); - if view == ArtifactView::Head { - qb.push(",a.deleted "); - } - if view == ArtifactView::History { - qb.push("FROM artifact_revisions r WHERE r.community_id=") - .push_bind(*community.as_uuid()) - .push(" AND r.scope='community' AND NOT r.redacted AND r.community_event IS NOT NULL"); - } else { - // Drive current reads from typed heads, not every historical revision. - // LIMIT 1 keeps the PK lookup lateral so the planner cannot reverse - // the join and scan the tenant ledger before the bounded head page. - qb.push("FROM artifact_heads a JOIN LATERAL (SELECT r.artifact_id,r.community_event,r.modified_at,r.event_id,r.scope FROM artifact_revisions r WHERE r.community_id=a.community_id AND r.event_id=a.event_id AND NOT r.redacted AND r.community_event IS NOT NULL LIMIT 1) r ON r.scope=a.scope AND r.artifact_id=a.artifact_id WHERE a.community_id=") - .push_bind(*community.as_uuid()) - .push(" AND a.scope='community'"); - } - if view == ArtifactView::Current { - qb.push(" AND NOT a.deleted"); - } - for (name, values) in tags { - if view != ArtifactView::History && name == "type" { - if let [value] = values.as_slice() { - qb.push(" AND a.artifact_type=").push_bind(value); - } else { - qb.push(" AND a.artifact_type=ANY(") - .push_bind(values) - .push(")"); - } - continue; - } - if name == "d" { - let (predicate, ids) = if view == ArtifactView::History { - // History matched the signed tag exactly. Only the canonical - // UUID spelling can match an accepted revision. - ( - " AND r.artifact_id=ANY(", - values - .iter() - .filter_map(|v| canonical_uuid(v).ok()) - .collect::>(), - ) - } else { - ( - " AND a.artifact_id=ANY(", - values - .iter() - .filter_map(|v| v.parse().ok()) - .collect::>(), - ) - }; - qb.push(predicate).push_bind(ids).push(")"); - continue; - } - qb.push(" AND EXISTS(SELECT 1 FROM jsonb_array_elements(r.community_event->'tags') tag WHERE tag->>0=").push_bind(name).push(" AND tag->>1=ANY(").push_bind(values).push("))"); - } - qb -} -pub(super) fn rows_to_events(rows: Vec) -> Result> { - rows.iter().map(row_to_event).collect() -} -fn row_to_event(row: &sqlx::postgres::PgRow) -> Result { - let event: Event = serde_json::from_value(row.try_get("community_event")?) - .map_err(|e| DbError::InvalidData(e.to_string()))?; - Ok(StoredEvent::with_received_at( - event, - row.try_get("modified_at")?, - None, - true, - )) -} -impl Db { - /// Explicit bounded community read; admission precedes filtering and paging. - pub async fn query_community_artifacts( - &self, - community: CommunityId, - principal: &CommunityArtifactPrincipal, - query: &ArtifactQuery, - ) -> Result> { - if query.scope != ArtifactScope::Community || query.view == ArtifactView::Policy { - return Err(denied()); - } - let mut tx = self - .begin_community_artifact_read(community, principal) - .await?; - let mut qb = query_builder(community, query.view, &query.tags); - qb.push(" ORDER BY r.modified_at DESC,r.event_id LIMIT ") - .push_bind(query.limit) - .push(" OFFSET ") - .push_bind(query.offset); - let events = rows_to_events(qb.build().fetch_all(&mut *tx).await?)?; - tx.commit().await?; - Ok(events) - } - /// Open a community complete-set snapshot on the writer, after live interest. - pub async fn open_community_artifact_snapshot( - &self, - community: CommunityId, - principal: &CommunityArtifactPrincipal, - ) -> Result { - // Reserve capacity for other writer-pool operations. - if self.pool.options().get_max_connections() < 2 { - return Err(DbError::ArtifactSyncLimit); - } - let permit = tokio::time::timeout( - std::time::Duration::from_secs(1), - self.community_artifact_snapshots.clone().acquire_owned(), - ) - .await - .map_err(|_| DbError::ArtifactSyncLimit)? - .map_err(|_| DbError::ArtifactSyncLimit)?; - let tx = self - .begin_community_artifact_read(community, principal) - .await?; - Ok(ArtifactSnapshot::for_community(tx, community, permit)) - } - /// Reload the current authorized head for a community change signal. - pub async fn community_artifact_head( - &self, - community: CommunityId, - principal: &CommunityArtifactPrincipal, - id: Uuid, - ) -> Result> { - let mut tx = self - .begin_community_artifact_read(community, principal) - .await?; - let mut query = query_builder(community, ArtifactView::Head, &[]); - query.push(" AND a.artifact_id=").push_bind(id); - let row = query.build().fetch_optional(&mut *tx).await?; - tx.commit().await?; - row.as_ref() - .map(|r| Ok((row_to_event(r)?, r.try_get("deleted")?))) - .transpose() - } - /// Redact only a community revision in this tenant. Keep its acceptance and - /// head ID. The same transaction writes the existing moderation audit row. - pub async fn redact_community_artifact( - &self, - community: CommunityId, - principal: &CommunityArtifactPrincipal, - target: &[u8], - ) -> Result> { - let mut tx = self.begin_event_write_transaction(community).await?; - set_admission_timeouts(tx.conn()).await?; - lock_restriction_writers(tx.conn(), community).await?; - lock_active_community(tx.conn(), community).await?; - let authority = authorize_members(tx.conn(), community, principal, false).await?; - if !authority.admin || authority.timed_out { - return Err(denied()); - } - let changed=sqlx::query("UPDATE artifact_revisions SET redacted=true WHERE community_id=$1 AND scope='community' AND event_id=$2 AND community_event IS NOT NULL AND NOT redacted") - .bind(community.as_uuid()).bind(target).execute(tx.conn()).await?.rows_affected()>0; - if changed { - sqlx::query("INSERT INTO moderation_actions(community_id,actor_pubkey,action,target_event_id,actor_authority) VALUES($1,$2,'delete_message',$3,'community')") - .bind(community.as_uuid()).bind(&principal.pubkey).bind(target).execute(tx.conn()).await?; - } else { - let exists: bool=sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM artifact_revisions WHERE community_id=$1 AND scope='community' AND event_id=$2 AND community_event IS NOT NULL)") - .bind(community.as_uuid()).bind(target).fetch_one(tx.conn()).await?; - if !exists { - return Err(DbError::NotFound("community artifact unavailable".into())); - } - } - // Lock the current head through commit so a historical redaction does - // not masquerade as retirement of a later revision. Concurrent CAS - // writers also lock this row before moving the head. - let retired = if changed { - sqlx::query_as::<_, (Uuid, String)>("SELECT artifact_id,artifact_type FROM artifact_heads WHERE community_id=$1 AND scope='community' AND event_id=$2 FOR UPDATE") - .bind(community.as_uuid()).bind(target).fetch_optional(tx.conn()).await? - } else { - None - }; - tx.commit().await?; - Ok(retired) - } -} - -#[cfg(test)] -mod postgres_tests { - use super::*; - use sqlx::Execute; - - #[tokio::test] - #[ignore = "requires Postgres"] - async fn community_artifact_history_can_seek_by_identity() { - let pool = sqlx::PgPool::connect(&crate::test_support::database_url()) - .await - .unwrap(); - if std::env::var("BUZZ_TEST_SCHEMA_MODE").as_deref() != Ok("desired") { - crate::migration::run_migrations(&pool).await.unwrap(); - } - let mut tx = pool.begin().await.unwrap(); - let community = CommunityId::from_uuid(Uuid::new_v4()); - sqlx::query("INSERT INTO communities(id,host) VALUES($1,$2)") - .bind(community.as_uuid()) - .bind(format!("history-plan-{community}.test")) - .execute(&mut *tx) - .await - .unwrap(); - let ids = [Uuid::new_v4(), Uuid::new_v4()]; - // Give the planner enough revisions in one community that locating a - // few identities through the index is cheaper than parsing every tag. - sqlx::query( - "INSERT INTO artifact_revisions(community_id,scope,event_id,artifact_id,community_event) \ - SELECT $1,'community',sha256(n::text::bytea),d, \ - jsonb_build_object('tags',jsonb_build_array(jsonb_build_array('d',d))) \ - FROM generate_series(1,2048) n \ - CROSS JOIN LATERAL (SELECT coalesce(($2::uuid[])[n],md5(n::text)::uuid) AS d) identity", - ) - .bind(community.as_uuid()) - .bind(ids.as_slice()) - .execute(&mut *tx) - .await - .unwrap(); - sqlx::query("ANALYZE artifact_revisions") - .execute(&mut *tx) - .await - .unwrap(); - let tags = [("d".into(), ids.iter().map(Uuid::to_string).collect())]; - let mut builder = query_builder(community, ArtifactView::History, &tags); - builder.push(" ORDER BY r.modified_at DESC,r.event_id LIMIT 50"); - let mut statement = builder.build(); - let arguments = statement.take_arguments().unwrap().unwrap(); - let explain = format!("EXPLAIN (FORMAT JSON) {}", statement.sql().as_str()); - let plan: Value = sqlx::query_scalar_with(sqlx::AssertSqlSafe(explain), arguments) - .fetch_one(&mut *tx) - .await - .unwrap(); - fn seeks_artifact(node: &Value) -> bool { - node["Index Cond"] - .as_str() - .is_some_and(|condition| condition.contains("artifact_id")) - || node["Plans"] - .as_array() - .is_some_and(|plans| plans.iter().any(seeks_artifact)) - } - assert!(seeks_artifact(&plan[0]["Plan"]), "{plan:#}"); - } -} diff --git a/crates/buzz-db/src/store/deletion.rs b/crates/buzz-db/src/store/deletion.rs index fec04ac0121..490d53cf6ad 100644 --- a/crates/buzz-db/src/store/deletion.rs +++ b/crates/buzz-db/src/store/deletion.rs @@ -2448,8 +2448,7 @@ impl DeletionStore { let tombstone: bool = sqlx::query_scalar( "SELECT EXISTS(SELECT 1 FROM communities WHERE id = $1 \ AND deletion_state = 'tombstone' AND deleted_at IS NOT NULL \ - AND deletion_fence_generation = $2 \ - AND COALESCE(to_jsonb(communities)->'artifact_type_policies' = '{}'::jsonb, true))", + AND deletion_fence_generation = $2)", ) .bind(token.community_id.as_uuid()) .bind(generation) @@ -3486,15 +3485,6 @@ async fn transition_community( } }; set_executor_gucs(tx, community, generation).await?; - // The community remains as a tombstone, so tenant policy state must be - // erased explicitly. Pre-expand schemas remain supported by deletion - // recovery; the schema/destruction lock keeps this catalog check stable. - if tombstone && sqlx::query_scalar::<_, bool>( - "SELECT EXISTS(SELECT 1 FROM pg_attribute WHERE attrelid='communities'::regclass AND attname='artifact_type_policies' AND NOT attisdropped)" - ).fetch_one(&mut **tx).await? { - sqlx::query("UPDATE communities SET artifact_type_policies='{}'::jsonb WHERE id=$1") - .bind(community.as_uuid()).execute(&mut **tx).await?; - } let affected = sqlx::query( "UPDATE communities SET deletion_state = $2, deletion_fence_generation = $3, \ archived_at = CASE WHEN $4 THEN COALESCE(archived_at, now()) ELSE $5 END, \ @@ -9140,16 +9130,6 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); .await .expect("seed operator feedback"); - sqlx::query("UPDATE communities SET artifact_type_policies='{\"example.settings\":{\"policy\":\"admins\",\"revision\":\"retained\"}}'::jsonb WHERE id=$1 AND deletion_state = 'active'") - .bind(community.as_uuid()).execute(&db.pool).await.unwrap(); - for (scope, byte) in [("channel", 10_u8), ("community", 11_u8)] { - let d = Uuid::new_v4(); - sqlx::query("INSERT INTO artifact_heads(community_id,scope,artifact_id,event_id,channel_id,artifact_type) VALUES($1,$2,$3,$4,$5,'example.settings')") - .bind(community.as_uuid()).bind(scope).bind(d).bind(vec![byte;32]).bind(channel).execute(&db.pool).await.unwrap(); - sqlx::query("INSERT INTO artifact_revisions(community_id,scope,artifact_id,event_id) VALUES($1,$2,$3,$4)") - .bind(community.as_uuid()).bind(scope).bind(d).bind(vec![byte;32]).execute(&db.pool).await.unwrap(); - } - store .approve(request.id, "approver", None) .await @@ -9263,20 +9243,6 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); ); assert_eq!(replayed.expect("replay accepted"), feedback_id); let deleted = purged.expect("purge without FK actions"); - assert_eq!(deleted.get("artifact_heads"), Some(&2)); - assert_eq!(deleted.get("artifact_revisions"), Some(&2)); - let policies: serde_json::Value = - sqlx::query_scalar("SELECT artifact_type_policies FROM communities WHERE id=$1") - .bind(community.as_uuid()) - .fetch_one(&db.pool) - .await - .unwrap(); - assert_eq!( - policies, - serde_json::json!({}), - "tombstones retain no artifact policies" - ); - for table in [ "channel_members", "personal_read_frontiers", @@ -9606,7 +9572,6 @@ DROP FUNCTION protect_community_deletion_manifest_keys(); .await .expect("bindings"); let deleted = store.purge_postgres(&token).await.expect("purge postgres"); - for table in PENDING_SCOPED_TABLES { assert_eq!(deleted.get(*table), Some(&1), "{table}"); } diff --git a/crates/buzz-db/src/store/event.rs b/crates/buzz-db/src/store/event.rs index 29ecad91de1..8d8d81b988f 100644 --- a/crates/buzz-db/src/store/event.rs +++ b/crates/buzz-db/src/store/event.rs @@ -783,12 +783,11 @@ fn build_query_events_sql( /// test, the channel scope (`push_channel_scope`) and the `#p` join, on /// columns qualified by `col_prefix` (`""` or `"e."`). fn push_event_filters(qb: &mut QueryBuilder, col_prefix: &str, q: &EventQuery) { - push_community_artifact_exclusion(qb, col_prefix); // Generic reads return only current artifact revisions, including delete // tombstones; explicit revision IDs also read earlier revisions. if q.ids.is_none() { let table = col_prefix.strip_suffix('.').unwrap_or("events"); - qb.push(format!(" AND NOT ({table}.kind = 45010 AND NOT EXISTS (SELECT 1 FROM artifact_heads ah WHERE ah.community_id={table}.community_id AND ah.event_id={table}.id AND ah.scope='channel'))")); + qb.push(format!(" AND NOT ({table}.kind = 45010 AND NOT EXISTS (SELECT 1 FROM artifact_heads ah WHERE ah.community_id={table}.community_id AND ah.event_id={table}.id))")); } push_notice_visibility(qb, col_prefix, q); @@ -1537,17 +1536,6 @@ pub(crate) fn row_to_stored_event(row: sqlx::postgres::PgRow) -> Result = row.try_get("received_at")?; let channel_id: Option = row.try_get("channel_id")?; - // Defense in depth for every hydration caller. Explicit community reads - // reconstruct their ledger payload only after community admission. - if kind_i32 == 45010 - && (channel_id.is_none() - || tags_json.as_array().is_none_or(|tags| { - tags.iter() - .any(|tag| tag.get(0).and_then(serde_json::Value::as_str) == Some("community")) - })) - { - return Ok(None); - } // kind is stored as i32 (Postgres INT) but Nostr uses u16. Values > 65535 are corrupt. let kind_u16 = u16::try_from(kind_i32) @@ -1651,12 +1639,11 @@ fn count_events_sql(q: &EventQuery) -> QueryBuilder { }; let col_prefix = if q.p_tag_hex.is_some() { "e." } else { "" }; - push_community_artifact_exclusion(&mut qb, col_prefix); // Generic reads return only current artifact revisions, including delete // tombstones; explicit revision IDs also read earlier revisions. if q.ids.is_none() { let table = if q.p_tag_hex.is_some() { "e" } else { "events" }; - qb.push(format!(" AND NOT ({table}.kind = 45010 AND NOT EXISTS (SELECT 1 FROM artifact_heads ah WHERE ah.community_id={table}.community_id AND ah.event_id={table}.id AND ah.scope='channel'))")); + qb.push(format!(" AND NOT ({table}.kind = 45010 AND NOT EXISTS (SELECT 1 FROM artifact_heads ah WHERE ah.community_id={table}.community_id AND ah.event_id={table}.id))")); } push_notice_visibility(&mut qb, col_prefix, q); @@ -1847,12 +1834,10 @@ pub(crate) async fn get_event_by_id_with_operation( operation: crate::observability::WriterOperation, ) -> Result> { let mut connection = crate::observability::acquire_writer(pool, operation).await?; - let row = sqlx::query(concat!( + let row = sqlx::query( "SELECT id, pubkey, created_at, kind, tags, content, sig, received_at, channel_id \ - FROM events WHERE community_id = $1 AND id = $2 AND (kind <> 45010 OR (channel_id IS NOT NULL AND NOT ", - crate::community_artifact_tag_sql!("tags"), - ")) AND deleted_at IS NULL ORDER BY created_at DESC LIMIT 1", - )) + FROM events WHERE community_id = $1 AND id = $2 AND deleted_at IS NULL ORDER BY created_at DESC LIMIT 1", + ) .bind(community_id.as_uuid()) .bind(id_bytes) .fetch_optional(&mut *connection) @@ -1926,12 +1911,10 @@ pub(crate) async fn get_event_by_id_including_deleted_with_operation( operation: crate::observability::WriterOperation, ) -> Result> { let mut connection = crate::observability::acquire_writer(pool, operation).await?; - let row = sqlx::query(concat!( + let row = sqlx::query( "SELECT id, pubkey, created_at, kind, tags, content, sig, received_at, channel_id \ - FROM events WHERE community_id = $1 AND id = $2 AND (kind <> 45010 OR (channel_id IS NOT NULL AND NOT ", - crate::community_artifact_tag_sql!("tags"), - ")) ORDER BY created_at DESC LIMIT 1", - )) + FROM events WHERE community_id = $1 AND id = $2 ORDER BY created_at DESC LIMIT 1", + ) .bind(community_id.as_uuid()) .bind(id_bytes) .fetch_optional(&mut *connection) @@ -1990,7 +1973,6 @@ pub(crate) async fn get_events_by_ids_on( FROM events WHERE community_id = ", ); qb.push_bind(community_id.as_uuid()); - push_community_artifact_exclusion(&mut qb, ""); qb.push(" AND deleted_at IS NULL AND id IN ("); let mut sep = qb.separated(", "); for id in ids { @@ -3105,10 +3087,7 @@ mod e_tag_filter_shape_tests { assert!(sql.starts_with("WITH m AS MATERIALIZED (SELECT ")); assert_eq!(sql.matches("tags @> ANY(").count(), 1); - // Audience predicates may contain OR; reference alternatives must - // remain one array-bound predicate inside the materialized fence. - assert!(!sql.contains(" OR tags @>")); - assert!(!sql.contains(" OR e.tags @>")); + assert!(!sql.contains(" OR ")); let fence_end = sql.find(") SELECT * FROM m ").expect("fence closes"); assert!(sql.contains("::jsonb[])")); assert!(!sql[..fence_end].contains("ORDER BY")); @@ -7435,17 +7414,3 @@ mod postgres_tests { ); } } - -/// Exclude the explicit community audience from every ordinary event surface, -/// even on disabled/bridge relays. A missing home also fails closed. This only -/// withholds data; it never derives or grants an audience from unsigned metadata. -fn push_community_artifact_exclusion(qb: &mut QueryBuilder, prefix: &str) { - let tag_sql = if prefix.is_empty() { - crate::community_artifact_tag_sql!("tags") - } else { - crate::community_artifact_tag_sql!("e.tags") - }; - qb.push(format!( - " AND ({prefix}kind <> 45010 OR ({prefix}channel_id IS NOT NULL AND NOT {tag_sql}))" - )); -} diff --git a/crates/buzz-db/src/store/mod.rs b/crates/buzz-db/src/store/mod.rs index 2a97d00edbe..e9c2e0d72bb 100644 --- a/crates/buzz-db/src/store/mod.rs +++ b/crates/buzz-db/src/store/mod.rs @@ -95,8 +95,6 @@ pub mod workflow; /// NIP-AR artifact lifecycle and durable delivery. pub mod artifact; -/// Explicit community artifact admission, policies and storage. -pub mod community_artifact; mod artifact_query; /// Timestamp-based incremental artifact reads. diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/artifact_postgres_tests.rs b/crates/buzz-db/src/store/user_deletion/content_batches/artifact_postgres_tests.rs deleted file mode 100644 index a81673da581..00000000000 --- a/crates/buzz-db/src/store/user_deletion/content_batches/artifact_postgres_tests.rs +++ /dev/null @@ -1,217 +0,0 @@ -//! User erasure must reach community payloads outside the conversation store. -use super::*; -use crate::{ - artifact::ArtifactOutcome, community_artifact::CommunityArtifactPrincipal, - user_deletion::ExecutionMode, CommunityId, Db, -}; -use buzz_core::artifact::{self, ArtifactQuery, ArtifactScope, ArtifactView}; -use nostr::{Event, EventBuilder, Keys, Kind, Tag}; - -fn principal(keys: &Keys) -> CommunityArtifactPrincipal { - CommunityArtifactPrincipal { - pubkey: keys.public_key().to_bytes().to_vec(), - verified_owner: None, - owner_admission: false, - require_membership: false, - reject_required_nip_fi: false, - } -} - -async fn revision( - db: &Db, - community: CommunityId, - id: Uuid, - author: &Keys, - previous: Option<&Event>, -) -> Event { - let mut tags = vec![ - vec!["ar".into(), "1".into()], - vec!["community".into(), community.to_string()], - vec!["d".into(), id.to_string()], - vec!["type".into(), "example.note".into()], - vec!["title".into(), "Personal data".into()], - vec![ - "op".into(), - if previous.is_some() { - "update" - } else { - "create" - } - .into(), - ], - ]; - if let Some(previous) = previous { - tags.push(vec!["prev".into(), previous.id.to_hex()]); - } - let event = EventBuilder::new(Kind::Custom(45010), "private authored payload") - .tags(tags.into_iter().map(|tag| Tag::parse(tag).unwrap())) - .sign_with_keys(author) - .unwrap(); - assert!(matches!( - db.accept_community_artifact( - community, - &principal(author), - &event, - &artifact::validate(&event).unwrap() - ) - .await - .unwrap(), - ArtifactOutcome::Accepted(_) - )); - event -} - -#[tokio::test] -#[ignore = "requires Postgres"] -async fn user_deletion_erases_community_artifact_payloads_without_resurrecting_heads() { - let (db, community, _, alice, bob) = super::scrub_postgres_tests::setup().await; - let other = db - .ensure_configured_community(&format!("artifact-erasure-{}.example", Uuid::new_v4())) - .await - .unwrap() - .id; - let agent = Keys::generate(); - db.ensure_user(community, agent.public_key().as_bytes()) - .await - .unwrap(); - db.set_agent_owner( - community, - agent.public_key().as_bytes(), - alice.public_key().as_bytes(), - ) - .await - .unwrap(); - let shared = Uuid::new_v4(); - let erased_head = Uuid::new_v4(); - let agent_id = Uuid::new_v4(); - let alice_old = revision(&db, community, shared, &alice, None).await; - let bob_head = revision(&db, community, shared, &bob, Some(&alice_old)).await; - let bob_old = revision(&db, community, erased_head, &bob, None).await; - let alice_head = revision(&db, community, erased_head, &alice, Some(&bob_old)).await; - let agent_head = revision(&db, community, agent_id, &agent, None).await; - let foreign = revision(&db, other, erased_head, &alice, None).await; - // Previously moderated payloads still contain personal data and belong in - // erasure, even though ordinary reads already suppress them. - sqlx::query( - "UPDATE artifact_revisions SET redacted=true WHERE community_id=$1 AND event_id=$2", - ) - .bind(community.as_uuid()) - .bind(alice_old.id.as_bytes().as_slice()) - .execute(db.pool()) - .await - .unwrap(); - let options = super::scrub_postgres_tests::options(community, &alice); - let store = db.user_deletion_store(); - store - .run_message_batches(&options, ExecutionMode::ReadOnly, None, &mut Vec::new()) - .await - .unwrap(); - assert!( - db.community_artifact_head(community, &principal(&bob), erased_head) - .await - .unwrap() - .is_some(), - "preview must not erase the current revision" - ); - let summary = store - .run_message_batches(&options, ExecutionMode::Delete, None, &mut Vec::new()) - .await - .unwrap(); - assert!( - db.community_artifact_head(community, &principal(&bob), erased_head) - .await - .unwrap() - .is_none(), - "erasure must hide the author's current head without reviving Bob's old revision" - ); - assert!( - db.community_artifact_head(community, &principal(&bob), agent_id) - .await - .unwrap() - .is_none(), - "owned-agent payloads must be erased too" - ); - assert_eq!( - db.community_artifact_head(community, &principal(&bob), shared) - .await - .unwrap() - .unwrap() - .0 - .event - .id, - bob_head.id - ); - let history = db - .query_community_artifacts( - community, - &principal(&bob), - &ArtifactQuery { - scope: ArtifactScope::Community, - view: ArtifactView::History, - tags: vec![], - limit: 100, - offset: 0, - }, - ) - .await - .unwrap(); - assert_eq!( - history - .iter() - .map(|event| event.event.id) - .collect::>(), - [bob_head.id, bob_old.id].into_iter().collect() - ); - assert_eq!( - db.community_artifact_head(other, &principal(&bob), erased_head) - .await - .unwrap() - .unwrap() - .0 - .event, - foreign, - "erasure is confined to its selected community" - ); - for event in [&alice_old, &alice_head, &agent_head] { - let (payload, redacted): (Option, bool) = sqlx::query_as( - "SELECT community_event,redacted FROM artifact_revisions WHERE community_id=$1 AND event_id=$2") - .bind(community.as_uuid()).bind(event.id.as_bytes().as_slice()) - .fetch_one(db.pool()).await.unwrap(); - assert!( - payload.is_none() && redacted, - "erase payload but preserve acceptance receipt" - ); - assert!( - db.community_artifact_accepted( - community, - &principal(if event.pubkey == agent.public_key() { - &agent - } else { - &alice - }), - event - ) - .await - .unwrap(), - "exact accepted replay remains recognized" - ); - } - let current: Vec = sqlx::query_scalar( - "SELECT event_id FROM artifact_heads WHERE community_id=$1 AND scope='community' AND artifact_id=$2") - .bind(community.as_uuid()).bind(erased_head).fetch_one(db.pool()).await.unwrap(); - assert_eq!( - current, - alice_head.id.as_bytes().to_vec(), - "the erased head remains the CAS predecessor" - ); - assert_eq!(summary.items, 3); - assert_eq!( - store - .run_message_batches(&options, ExecutionMode::Delete, None, &mut Vec::new()) - .await - .unwrap() - .items, - 0, - "erasure retry converges" - ); -} diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/execute.rs b/crates/buzz-db/src/store/user_deletion/content_batches/execute.rs index bde4c23865b..a089bc57f11 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/execute.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/execute.rs @@ -98,7 +98,6 @@ pub(super) fn items(batch: &Value) -> Result<&Vec> { pub(super) fn selection(item: &Value) -> Result<(&'static str, &'static str)> { Ok(match item["table"].as_str() { Some("events") => ("events", "id=decode($2->>'id','hex') AND created_at=($2->>'created_at')::timestamptz"), - Some("artifact_revisions") => ("artifact_revisions", "scope='community' AND event_id=decode($2->>'event_id','hex')"), Some("reactions") => ("reactions", "event_id=decode($2->>'event_id','hex') AND event_created_at=($2->>'event_created_at')::timestamptz AND pubkey=decode($2->>'pubkey','hex') AND emoji=$2->>'emoji'"), Some("event_mentions") => ("event_mentions", "event_id=decode($2->>'event_id','hex') AND pubkey_hex=$2->>'pubkey_hex'"), Some("push_match_queue") => ("push_match_queue", "event_id=decode($2->>'event_id','hex')"), diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/grouped.rs b/crates/buzz-db/src/store/user_deletion/content_batches/grouped.rs index 6f5226adaac..f3873bf2b86 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/grouped.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/grouped.rs @@ -115,8 +115,6 @@ pub(super) async fn execute(tx: &mut AdmittedTx, batch: &Value) -> Result<()> { children(tx.conn(), community, number, table).await?; if table == "events" { erase_events(tx, number).await?; - } else if table == "artifact_revisions" { - erase_community_artifacts(tx, number, expected).await?; } else { let query = format!( "DELETE FROM {table} t USING content_batch_work w @@ -140,44 +138,6 @@ pub(super) async fn execute(tx: &mut AdmittedTx, batch: &Value) -> Result<()> { Ok(()) } -async fn erase_community_artifacts( - tx: &mut AdmittedTx, - number: i64, - expected: usize, -) -> Result<()> { - let community = *tx.community().as_uuid(); - // Like channel event deletion, mark a matching head modified without - // changing its revision ID. Reads must not resurrect an older revision. - sqlx::query( - "UPDATE artifact_heads h SET modified_at=clock_timestamp() - FROM content_batch_work w WHERE w.table_name='artifact_revisions' AND w.batch=$2 - AND w.action='would_scrub' AND h.community_id=$1 AND h.scope='community' - AND h.event_id=decode(w.row_key->>'event_id','hex')", - ) - .bind(community) - .bind(number) - .execute(tx.conn()) - .await?; - let affected = sqlx::query( - "UPDATE artifact_revisions r SET community_event=NULL, - redacted=true,modified_at=clock_timestamp() FROM content_batch_work w - WHERE w.table_name='artifact_revisions' AND w.batch=$2 AND w.action='would_scrub' - AND r.community_id=$1 AND r.scope='community' - AND r.event_id=decode(w.row_key->>'event_id','hex')", - ) - .bind(community) - .bind(number) - .execute(tx.conn()) - .await? - .rows_affected(); - if affected as usize != expected { - return Err(invalid( - "artifact revisions changed; current batch rolled back", - )); - } - Ok(()) -} - async fn children( conn: &mut PgConnection, community: Uuid, @@ -290,7 +250,6 @@ pub(super) async fn verify_remaining( OR EXISTS(SELECT 1 FROM subscriptions WHERE community_id=$1 AND owner_pubkey=ANY($2)) OR EXISTS(SELECT 1 FROM push_leases WHERE community_id=$1 AND author=ANY($2)) OR EXISTS(SELECT 1 FROM push_wake_outbox WHERE community_id=$1 AND author=ANY($2)) - OR EXISTS(SELECT 1 FROM artifact_revisions WHERE community_id=$1 AND {COMMUNITY_ARTIFACT_AUTHOR_PREDICATE}) OR EXISTS(SELECT 1 FROM operator_listener_outbox WHERE community_id=$1 AND (target_pubkey=ANY($2) OR listener_pubkey=ANY($2)))",include_str!("authored.sql")); let remains: bool = sqlx::query_scalar(sqlx::AssertSqlSafe(query)) .bind(options.community) diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs b/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs index 1cfb80f901d..f685d96f0c3 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/mod.rs @@ -32,10 +32,6 @@ const KINDS: &[i32] = &[ const PAGE_SIZE: i64 = 100; const MAX_TARGETS: usize = 10_000; const EVENT_COLUMNS: &str = "e.id,e.created_at,e.channel_id,e.kind,e.tags"; -// Shared with profile cleanup's content-before-profile dependency gate. -pub(super) const COMMUNITY_ARTIFACT_AUTHOR_PREDICATE: &str = - "scope='community' AND community_event IS NOT NULL AND community_event->>'pubkey' IN - (SELECT encode(target.pubkey,'hex') FROM unnest($2::bytea[]) target(pubkey))"; /// Scope and bounds for standalone preview or explicitly requested deletion. pub struct ContentBatchOptions { @@ -247,7 +243,7 @@ async fn plan( "excluded_agents": excluded_agents, "target_pubkeys": target_pubkeys, "trusted_relay_pubkey": relay, "included_event_kinds": KINDS, "batch_size": options.batch_size, "max_items": options.max_items, - "scope": "user- and owned-agent-attributed events (including persona, team, emoji and project definitions), community artifact revisions and reactions, owned subscriptions and notification delivery", + "scope": "user- and owned-agent-attributed events (including persona, team, emoji and project definitions) and reactions, owned subscriptions and notification delivery", "preserved": "other users' events and reactions; member repositories; workflow database records and other owners' delivery logs", "relay_attribution": if relay.is_some() { "enabled" } else { "not included; supply --relay-pubkey for relay-authored history" }, "execution": "preview only; --delete prints and commits batches after execution checks", @@ -362,6 +358,3 @@ mod scrub_postgres_tests; #[cfg(test)] mod safety_postgres_tests; - -#[cfg(test)] -mod artifact_postgres_tests; diff --git a/crates/buzz-db/src/store/user_deletion/content_batches/owned.rs b/crates/buzz-db/src/store/user_deletion/content_batches/owned.rs index ad3a567a3c3..c2055e49d59 100644 --- a/crates/buzz-db/src/store/user_deletion/content_batches/owned.rs +++ b/crates/buzz-db/src/store/user_deletion/content_batches/owned.rs @@ -8,11 +8,6 @@ pub(super) async fn plan( output: &mut Output<'_, impl Write>, ) -> Result<()> { let reason = json!({"type": "owned_resource"}); - // Community artifact payloads live outside events. Keep their acceptance - // receipts, exactly as channel artifacts keep theirs after event erasure. - rows(conn, output, "artifact_revisions", &format!("SELECT jsonb_build_object('event_id',encode(event_id,'hex')) AS row_key, - NULL::text AS warning FROM artifact_revisions WHERE community_id=$1 AND {COMMUNITY_ARTIFACT_AUTHOR_PREDICATE}"), - targets, &reason, "would_scrub").await?; // Workflow state can contain another user's approvals or work. Leave it // intact in this initial ownership-only content pass. rows( diff --git a/crates/buzz-db/src/store/user_deletion/profile_batches/plan.rs b/crates/buzz-db/src/store/user_deletion/profile_batches/plan.rs index ae27f15364f..6255115b9ed 100644 --- a/crates/buzz-db/src/store/user_deletion/profile_batches/plan.rs +++ b/crates/buzz-db/src/store/user_deletion/profile_batches/plan.rs @@ -107,7 +107,6 @@ pub(super) async fn dependencies(conn: &mut PgConnection, scope: &Scope) -> Resu ("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)"), - ("artifact_revisions",super::super::content_batches::COMMUNITY_ARTIFACT_AUTHOR_PREDICATE), ("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}))"); diff --git a/crates/buzz-db/tests/observability_source.rs b/crates/buzz-db/tests/observability_source.rs index 7b75dae59bd..f85af28be13 100644 --- a/crates/buzz-db/tests/observability_source.rs +++ b/crates/buzz-db/tests/observability_source.rs @@ -4068,7 +4068,6 @@ fn every_production_single_table_guard_writer_preserves_its_invariants() { "ensure_configured_community_with_operation", "set_community_icon", "set_community_nip_fi_policy", - "set_policy_in_transaction", "soft_delete_on", "unarchive_community_owned_by", "update_channel_on", diff --git a/crates/buzz-pubsub/src/artifact_signal.rs b/crates/buzz-pubsub/src/artifact_signal.rs deleted file mode 100644 index 4e994ab8f2e..00000000000 --- a/crates/buzz-pubsub/src/artifact_signal.rs +++ /dev/null @@ -1,59 +0,0 @@ -//! Compact community artifact invalidations; never signed event payloads. -use buzz_core::{CommunityId, TenantContext}; -use serde::{Deserialize, Serialize}; -use uuid::Uuid; - -/// Why a community artifact identity needs a fresh authorized head read. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum ArtifactChange { - /// A revision committed, including an artifact deletion revision. - Changed, - /// The current head was redacted; an exact copy must resync. - Redacted, -} - -/// Bounded metadata for one immutable type and artifact identity. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct ArtifactSignal { - /// Scoped artifact identity. - pub d: Uuid, - /// Immutable artifact type. - #[serde(rename = "type")] - pub artifact_type: String, - /// Change or current-head redaction. - pub cause: ArtifactChange, -} -impl ArtifactSignal { - pub(crate) fn decode(payload: &str) -> Result { - let signal: Self = serde_json::from_str(payload)?; - buzz_core::artifact::validate_type(&signal.artifact_type) - .map_err(|_| crate::PubSubError::InvalidChannelKey("invalid artifact type".into()))?; - Ok(signal) - } -} - -/// A signal bound to the server-resolved Redis topic's tenant. -#[derive(Debug, Clone)] -pub struct ScopedArtifactSignal { - /// Tenant from the topic, never from the payload. - pub community_id: CommunityId, - /// Compact change metadata. - pub signal: ArtifactSignal, -} - -/// Publish compact metadata only on the dedicated tenant artifact topic. -pub async fn publish( - pool: &crate::RedisConnection, - tenant: &TenantContext, - signal: &ArtifactSignal, -) -> Result { - let key = crate::EventTopicKey::from_context(tenant, crate::EventTopic::CommunityArtifact) - .redis_channel(); - Ok(redis::cmd("PUBLISH") - .arg(key) - .arg(serde_json::to_string(signal)?) - .query_async(&mut pool.clone()) - .await?) -} diff --git a/crates/buzz-pubsub/src/lib.rs b/crates/buzz-pubsub/src/lib.rs index 38fc825ba7a..e7f85d53801 100644 --- a/crates/buzz-pubsub/src/lib.rs +++ b/crates/buzz-pubsub/src/lib.rs @@ -21,8 +21,6 @@ //! The shared [`RedisConnection`] handles all other commands. //! Lagged receivers get `RecvError::Lagged`. -/// Compact tenant-scoped artifact change signals. -pub mod artifact_signal; /// Cross-pod cache-key invalidation over Redis pub/sub. pub mod cache_invalidation; /// Cross-pod connection-control commands over Redis pub/sub. @@ -139,7 +137,6 @@ pub struct PubSubManager { /// Coalesced wake-up: reconcile desired topics with the live Redis link. subscription_changed: Arc, broadcast_tx: broadcast::Sender, - artifact_tx: broadcast::Sender, cache_invalidation_tx: broadcast::Sender, conn_control_tx: broadcast::Sender, nip_fi_disconnect_tx: broadcast::Sender, @@ -158,7 +155,6 @@ impl PubSubManager { pool: crate::RedisConnection, ) -> Result { let (broadcast_tx, _) = broadcast::channel(4096); - let (artifact_tx, _) = broadcast::channel(4096); let (cache_invalidation_tx, _) = broadcast::channel(4096); let (conn_control_tx, _) = broadcast::channel(4096); let (nip_fi_disconnect_tx, _) = broadcast::channel(4096); @@ -173,7 +169,6 @@ impl PubSubManager { subscription_rx: Mutex::new(Some(subscription_rx)), subscription_changed: Arc::new(Notify::new()), broadcast_tx, - artifact_tx, cache_invalidation_tx, conn_control_tx, nip_fi_disconnect_tx, @@ -194,7 +189,6 @@ impl PubSubManager { subscriber::run_subscriber( self.redis_url.clone(), self.broadcast_tx.clone(), - self.artifact_tx.clone(), self.desired_topics.clone(), subscription_rx, self.subscription_changed.clone(), @@ -246,22 +240,6 @@ impl PubSubManager { self.broadcast_tx.subscribe() } - /// Receive compact signals from the same subscriber and loss epoch as events. - pub fn subscribe_artifacts( - &self, - ) -> broadcast::Receiver { - self.artifact_tx.subscribe() - } - - /// Publish a compact artifact signal, without using ordinary event fan-out. - pub async fn publish_artifact( - &self, - tenant: &TenantContext, - signal: &artifact_signal::ArtifactSignal, - ) -> Result { - artifact_signal::publish(&self.pool, tenant, signal).await - } - /// Retain local interest in a scoped Redis event topic. /// /// The first retain for a topic asks the subscriber task to `SUBSCRIBE`. @@ -538,7 +516,7 @@ mod tests { use super::*; use crate::test_util::make_test_pool; use buzz_core::{CommunityId, TenantContext}; - use nostr::{EventBuilder, JsonUtil, Keys, Kind}; + use nostr::{EventBuilder, Keys, Kind}; use uuid::Uuid; async fn make_manager() -> Arc { @@ -561,8 +539,8 @@ mod tests { let mut rx = manager.subscribe_local(); let manager_clone = manager.clone(); - let subscriber = tokio::spawn(async move { manager_clone.run_subscriber().await }); - manager.link_state().wait_for(|link| link.up).await.unwrap(); + tokio::spawn(async move { manager_clone.run_subscriber().await }); + tokio::time::sleep(tokio::time::Duration::from_millis(200)).await; let ctx = ctx(0xaaaa, "a.example"); let channel_id = Uuid::new_v4(); @@ -576,10 +554,6 @@ mod tests { manager .retain_topic(&ctx, EventTopic::Channel(channel_id)) .await; - manager - .confirm_topic(&ctx, EventTopic::Channel(channel_id)) - .await - .unwrap(); manager .publish_event(&ctx, EventTopic::Channel(channel_id), &event) @@ -594,53 +568,6 @@ mod tests { assert_eq!(received.community_id, ctx.community()); assert_eq!(received.topic, EventTopic::Channel(channel_id)); assert_eq!(received.event.id, event_id); - let mut signals = manager.subscribe_artifacts(); - manager - .retain_topic(&ctx, EventTopic::CommunityArtifact) - .await; - let epoch = manager - .confirm_topic(&ctx, EventTopic::CommunityArtifact) - .await - .unwrap(); - let signal = artifact_signal::ArtifactSignal { - d: Uuid::new_v4(), - artifact_type: "example.settings".into(), - cause: artifact_signal::ArtifactChange::Changed, - }; - manager.publish_artifact(&ctx, &signal).await.unwrap(); - let received = tokio::time::timeout(Duration::from_secs(2), signals.recv()) - .await - .unwrap() - .unwrap(); - assert_eq!(received.community_id, ctx.community()); - assert_eq!(received.signal, signal); - assert!( - rx.try_recv().is_err(), - "typed signal cannot enter ordinary event fan-out" - ); - // A signed event on the signal topic is a decode loss, never a fake - // signal. Existing epoch observers must resync their exact copies. - let key = EventTopicKey::from_context(&ctx, EventTopic::CommunityArtifact).redis_channel(); - let mut link = manager.link_state(); - redis::cmd("PUBLISH") - .arg(key) - .arg(event.as_json()) - .query_async::(&mut manager.pool.clone()) - .await - .unwrap(); - tokio::time::timeout( - Duration::from_secs(2), - link.wait_for(|link| link.epoch != epoch), - ) - .await - .unwrap() - .unwrap(); - assert!(signals.try_recv().is_err()); - assert!(rx.try_recv().is_err()); - manager - .release_topic(&ctx, EventTopic::CommunityArtifact) - .await; - subscriber.abort(); } #[tokio::test] diff --git a/crates/buzz-pubsub/src/subscriber.rs b/crates/buzz-pubsub/src/subscriber.rs index 1d814cb5d2b..49cd27417d3 100644 --- a/crates/buzz-pubsub/src/subscriber.rs +++ b/crates/buzz-pubsub/src/subscriber.rs @@ -49,7 +49,6 @@ fn mark_loss(link: &watch::Sender, up: bool) { pub(crate) async fn run_subscriber( redis_url: String, broadcast_tx: broadcast::Sender, - artifact_tx: broadcast::Sender, desired_topics: DesiredTopics, mut subscription_rx: mpsc::Receiver, subscription_changed: Arc, @@ -61,7 +60,6 @@ pub(crate) async fn run_subscriber( let result = connect_and_subscribe( &redis_url, &broadcast_tx, - &artifact_tx, desired_topics.clone(), &mut subscription_rx, &subscription_changed, @@ -97,7 +95,6 @@ pub(crate) async fn run_subscriber( async fn connect_and_subscribe( redis_url: &str, broadcast_tx: &broadcast::Sender, - artifact_tx: &broadcast::Sender, desired_topics: DesiredTopics, subscription_rx: &mut mpsc::Receiver, subscription_changed: &Notify, @@ -190,18 +187,6 @@ async fn connect_and_subscribe( } }; - if topic_key.topic == crate::EventTopic::CommunityArtifact { - match crate::artifact_signal::ArtifactSignal::decode(&payload) { - Ok(signal) => { let _ = artifact_tx.send(crate::artifact_signal::ScopedArtifactSignal { - community_id: topic_key.community_id, signal, - }); } - Err(error) => { - tracing::warn!(%error, "Invalid artifact signal"); - mark_loss(link, true); - } - } - continue; - } let event = match nostr::Event::from_json(&payload) { Ok(e) => e, Err(e) => { diff --git a/crates/buzz-pubsub/src/topic.rs b/crates/buzz-pubsub/src/topic.rs index 6666221b05d..07cabf9eca5 100644 --- a/crates/buzz-pubsub/src/topic.rs +++ b/crates/buzz-pubsub/src/topic.rs @@ -19,8 +19,6 @@ pub enum EventTopic { Channel(Uuid), /// Community-global events that are not exact-channel routed. Global, - /// Compact artifact signals, isolated from ordinary event fan-out. - CommunityArtifact, } /// A fully qualified event topic, including its server-resolved community. @@ -48,9 +46,6 @@ impl EventTopicKey { format!("{BUZZ_PREFIX}:{}:channel:{channel_id}", self.community_id) } EventTopic::Global => format!("{BUZZ_PREFIX}:{}:global", self.community_id), - EventTopic::CommunityArtifact => { - format!("{BUZZ_PREFIX}:{}:artifacts", self.community_id) - } } } @@ -76,7 +71,6 @@ impl EventTopicKey { }; let topic = match scope { - "artifacts" if parts.next().is_none() => EventTopic::CommunityArtifact, "global" => { if parts.next().is_some() { return Err(PubSubError::InvalidChannelKey(channel.to_string())); diff --git a/crates/buzz-relay/src/api/admin/mod.rs b/crates/buzz-relay/src/api/admin/mod.rs index 14f9777763e..c29797185b6 100644 --- a/crates/buzz-relay/src/api/admin/mod.rs +++ b/crates/buzz-relay/src/api/admin/mod.rs @@ -1498,7 +1498,6 @@ fn summarize_body(body: &str, tags: &serde_json::Value) -> String { #[cfg(test)] mod postgres_tests { - mod artifact_direct_postgres_tests; use super::*; use auth::ADMIN_API_PREFIX; use axum::{ @@ -12007,6 +12006,43 @@ mod postgres_tests { assert_eq!(live, 0); } + /// An artifact revision is not admin-deletable: open NIP-AR syncs would + /// get no live signal (they see `op=delete` and kind 9005). The action + /// fails terminally and the head stays. Mutation: drop the kind check in + /// `execute_delete_with_marker` → 200 and the head is gone → RED. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn direct_delete_refuses_artifact_revisions() { + let (pool, community, host, state) = direct_fixture().await; + let id = seed_signed_event(&pool, community, &test_operator_keys()).await; + sqlx::query("UPDATE events SET kind = 45010 WHERE community_id = $1") + .bind(community.as_uuid()) + .execute(&pool) + .await + .unwrap(); + let path = format!("/events/{id}/delete?communityHost={host}"); + let (status, body) = direct_post( + &state, + &path, + serde_json::json!({ "requestId": Uuid::new_v4() }), + ) + .await; + assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{body}"); + assert!( + body.to_string() + .contains("artifact revisions cannot be deleted"), + "{body}" + ); + let live: i64 = sqlx::query_scalar( + "SELECT COUNT(*) FROM events WHERE community_id = $1 AND deleted_at IS NULL", + ) + .bind(community.as_uuid()) + .fetch_one(&pool) + .await + .unwrap(); + assert_eq!(live, 1); + } + /// F1: attempt B passes the stored-action lookup, attempt A (same request) /// accepts and deletes, then B validates against a gone event. B must /// replay A (200), and a B carrying a different intent must get 409 — diff --git a/crates/buzz-relay/src/api/admin/postgres_tests/artifact_direct_postgres_tests.rs b/crates/buzz-relay/src/api/admin/postgres_tests/artifact_direct_postgres_tests.rs deleted file mode 100644 index f478f21901d..00000000000 --- a/crates/buzz-relay/src/api/admin/postgres_tests/artifact_direct_postgres_tests.rs +++ /dev/null @@ -1,59 +0,0 @@ -//! The direct moderation guard uses a real signed channel artifact fixture. -mod postgres_tests { - use super::super::*; - /// An artifact revision is not admin-deletable: open NIP-AR syncs would - /// get no live signal (they see `op=delete` and kind 9005). The action - /// fails terminally and the head stays. Mutation: drop the kind check in - /// `execute_delete_with_marker` → 200 and the head is gone → RED. - #[tokio::test] - #[ignore = "requires Postgres"] - async fn direct_delete_refuses_artifact_revisions() { - let (pool, community, host, state) = direct_fixture().await; - // Seed a signed channel revision. A channel-less note with only its - // database kind changed has no artifact audience and now fails closed - // before the direct-action guard, so it cannot exercise this contract. - let home = Uuid::new_v4(); - let keys = test_operator_keys(); - sqlx::query("INSERT INTO channels(community_id,id,name,channel_type,visibility,created_by) VALUES($1,$2,'direct-artifact','stream','open',$3)") - .bind(community.as_uuid()).bind(home).bind(keys.public_key().as_bytes().as_slice()) - .execute(&pool).await.unwrap(); - let event = nostr::EventBuilder::new(nostr::Kind::Custom(45010), "channel artifact") - .tags([ - nostr::Tag::parse(["ar", "1"]).unwrap(), - nostr::Tag::parse(["h", &home.to_string()]).unwrap(), - nostr::Tag::parse(["d", &Uuid::new_v4().to_string()]).unwrap(), - nostr::Tag::parse(["type", "example.settings"]).unwrap(), - nostr::Tag::parse(["title", "Direct artifact"]).unwrap(), - nostr::Tag::parse(["op", "create"]).unwrap(), - ]) - .sign_with_keys(&keys) - .unwrap(); - state - .db - .insert_event(community, &event, Some(home)) - .await - .unwrap(); - let id = event.id.to_hex(); - let path = format!("/events/{id}/delete?communityHost={host}"); - let (status, body) = direct_post( - &state, - &path, - serde_json::json!({ "requestId": Uuid::new_v4() }), - ) - .await; - assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{body}"); - assert!( - body.to_string() - .contains("artifact revisions cannot be deleted"), - "{body}" - ); - let live: i64 = sqlx::query_scalar( - "SELECT COUNT(*) FROM events WHERE community_id = $1 AND deleted_at IS NULL", - ) - .bind(community.as_uuid()) - .fetch_one(&pool) - .await - .unwrap(); - assert_eq!(live, 1); - } -} diff --git a/crates/buzz-relay/src/api/artifact.rs b/crates/buzz-relay/src/api/artifact.rs index df07e1371d7..7284563be8b 100644 --- a/crates/buzz-relay/src/api/artifact.rs +++ b/crates/buzz-relay/src/api/artifact.rs @@ -14,7 +14,7 @@ use std::sync::Arc; pub(super) async fn query( state: &Arc, tenant: &TenantContext, - caller: &super::bridge::ProvenCaller, + reader: &nostr::PublicKey, filters: &[Value], count: bool, routed: impl FnOnce(), @@ -34,7 +34,7 @@ pub(super) async fn query( Ok(false) => None, Ok(true) => { routed(); - Some(execute(state, tenant, caller, filters, count).await) + Some(execute(state, tenant, reader, filters, count).await) } Err(reason) => { routed(); @@ -46,11 +46,10 @@ pub(super) async fn query( async fn execute( state: &Arc, tenant: &TenantContext, - caller: &super::bridge::ProvenCaller, + reader: &nostr::PublicKey, filters: &[Value], count: bool, ) -> Result, (StatusCode, Json)> { - let reader = &caller.pubkey; // One filter avoids ambiguous OR-union count/page semantics. AND/OR inside // exact predicates still supports cross-channel multi-value lists. if filters.len() != 1 { @@ -70,60 +69,6 @@ async fn execute( } let query = buzz_core::artifact::parse_query(&filters[0]) .map_err(|e| api_error(StatusCode::BAD_REQUEST, e))?; - if query.scope == buzz_core::artifact::ArtifactScope::Community { - if count { - return Err(api_error( - StatusCode::BAD_REQUEST, - "community artifact count is unsupported", - )); - } - if caller.signed_at.is_none() { - return Err(api_error( - StatusCode::UNAUTHORIZED, - "community artifacts require signed HTTP authentication", - )); - } - if !crate::handlers::community_artifact::enabled(state) - .await - .unwrap_or(false) - { - return Err(api_error( - StatusCode::SERVICE_UNAVAILABLE, - "community artifacts unavailable", - )); - } - let principal = buzz_db::community_artifact::CommunityArtifactPrincipal { - owner_admission: true, - pubkey: reader.to_bytes().to_vec(), - verified_owner: caller - .token_owner - .or(caller.artifact_owner) - .map(|p| p.to_bytes().to_vec()), - require_membership: state.config.require_relay_membership, - reject_required_nip_fi: false, - }; - if query.view == buzz_core::artifact::ArtifactView::Policy { - let artifact_type = buzz_core::artifact::exact_type(&query.tags) - .map_err(|e| api_error(StatusCode::BAD_REQUEST, e))?; - let policy = state - .db - .community_artifact_policy(tenant.community(), &principal, artifact_type) - .await - .map_err(community_error)?; - return Ok(Json(serde_json::json!(policy))); - } - let events = state - .db - .query_community_artifacts(tenant.community(), &principal, &query) - .await - .map_err(community_error)?; - return Ok(Json(Value::Array( - events - .into_iter() - .map(|e| serde_json::json!(e.event)) - .collect(), - ))); - } // The query's statement_timeout is the enforced execution budget. let (events, n) = state .db @@ -150,12 +95,3 @@ async fn execute( })?; Ok(Json(Value::Array(events))) } - -fn community_error(error: buzz_db::DbError) -> (StatusCode, Json) { - let status = if matches!(error, buzz_db::DbError::AccessDenied(_)) { - StatusCode::FORBIDDEN - } else { - StatusCode::SERVICE_UNAVAILABLE - }; - api_error(status, "community artifact read denied or unavailable") -} diff --git a/crates/buzz-relay/src/api/artifact_postgres_tests.rs b/crates/buzz-relay/src/api/artifact_postgres_tests.rs index 66bdfce4654..2519510cf4c 100644 --- a/crates/buzz-relay/src/api/artifact_postgres_tests.rs +++ b/crates/buzz-relay/src/api/artifact_postgres_tests.rs @@ -308,9 +308,7 @@ async fn lifecycle_routes_duplicate_replay_delete_and_redaction() { EventBuilder::new(Kind::Custom(kind), "") .tags([ Tag::parse(["e", &restore.id.to_hex()]).unwrap(), - // Legacy channel moderation accepts Uuid::parse_str forms - // and extra tag fields; community canonicality is independent. - Tag::parse(["h", &f.home.simple().to_string().to_uppercase(), "legacy"]).unwrap(), + Tag::parse(["h", &f.home.to_string()]).unwrap(), ]) .sign_with_keys(&f.owner) .unwrap() @@ -322,28 +320,6 @@ async fn lifecycle_routes_duplicate_replay_delete_and_redaction() { .contains("artifacts cannot be deleted with kind 5"), "{body}" ); - for scopes in [ - vec![], - vec![ - vec!["h".to_owned(), f.home.to_string()], - vec!["h".to_owned(), f.home.to_string()], - ], - vec![ - vec!["h".to_owned(), f.home.to_string()], - vec!["community".to_owned(), f.community.to_string()], - ], - vec![ - vec!["community".to_owned(), f.community.to_string()], - vec!["community".to_owned(), f.community.to_string()], - ], - ] { - let malformed = EventBuilder::new(Kind::Custom(9005), "") - .tags(scopes.into_iter().map(|t| Tag::parse(t).unwrap())) - .tag(Tag::event(restore.id)) - .sign_with_keys(&f.owner) - .unwrap(); - assert!(!f.request("/events", json!(malformed)).await.0.is_success()); - } // Redaction is the ordinary 9005 removal; the head stays editable. f.publish(&command(9005)).await; let current = json!([{"artifact":"current","#d":[d]}]); @@ -513,6 +489,3 @@ async fn generic_d_lookup_matches_before_limit() { #[path = "artifact_postgres_tests/sync_postgres_tests.rs"] mod sync_postgres_tests; - -#[path = "artifact_postgres_tests/community_postgres_tests.rs"] -mod community_postgres_tests; diff --git a/crates/buzz-relay/src/api/artifact_postgres_tests/community_postgres_tests.rs b/crates/buzz-relay/src/api/artifact_postgres_tests/community_postgres_tests.rs deleted file mode 100644 index 13d164931d6..00000000000 --- a/crates/buzz-relay/src/api/artifact_postgres_tests/community_postgres_tests.rs +++ /dev/null @@ -1,501 +0,0 @@ -//! Community operations through the production HTTP router, with real signed -//! NIP-98 bodies. TCP coverage below exercises the same serving router. -use super::*; -use axum::http::StatusCode; -use base64::Engine; -use sha2::Digest; - -async fn fixture() -> Fixture { - let mut f = Fixture::new().await; - Arc::make_mut(&mut Arc::get_mut(&mut f.state).unwrap().config).community_artifacts_enabled = - true; - let mut connection = f.pool.acquire().await.unwrap(); - sqlx::query( - "SET buzz.community_artifact_contract_ready='all-backends-enforce-community-audience'", - ) - .execute(&mut *connection) - .await - .unwrap(); - sqlx::raw_sql(include_str!( - "../../../../../scripts/maintenance/community-artifact-contract.sql" - )) - .execute(&mut *connection) - .await - .unwrap(); - sqlx::query("INSERT INTO relay_members(community_id,pubkey,role) VALUES($1,$2,'owner')") - .bind(f.community.as_uuid()) - .bind(f.owner.public_key().to_hex()) - .execute(&f.pool) - .await - .unwrap(); - f -} -fn revision(f: &Fixture, keys: &Keys, d: Uuid, op: &str, prev: Option<&Event>) -> Event { - let mut tags = vec![ - vec!["ar".into(), "1".into()], - vec!["community".into(), f.community.to_string()], - vec!["d".into(), d.to_string()], - vec!["type".into(), "example.settings".into()], - vec!["op".into(), op.into()], - ]; - if op != "delete" { - tags.push(vec!["title".into(), "Settings".into()]); - } - if let Some(prev) = prev { - tags.push(vec!["prev".into(), prev.id.to_hex()]); - } - EventBuilder::new( - Kind::Custom(45010), - if op == "delete" { - "" - } else { - "private artifact needle" - }, - ) - .tags(tags.into_iter().map(|tag| Tag::parse(tag).unwrap())) - .sign_with_keys(keys) - .unwrap() -} -fn authorization(f: &Fixture, keys: &Keys, path: &str, bytes: &[u8]) -> String { - let event = EventBuilder::new(Kind::Custom(27235), "") - .tags([ - Tag::parse(["u", &format!("https://{}{path}", f.host)]).unwrap(), - Tag::parse(["method", "POST"]).unwrap(), - Tag::parse(["payload", &hex::encode(sha2::Sha256::digest(bytes))]).unwrap(), - Tag::parse(["nonce", &Uuid::new_v4().to_string()]).unwrap(), - ]) - .sign_with_keys(keys) - .unwrap(); - format!( - "Nostr {}", - base64::engine::general_purpose::STANDARD.encode(serde_json::to_vec(&event).unwrap()) - ) -} -async fn signed(f: &Fixture, keys: &Keys, path: &str, body: Value) -> (StatusCode, Value) { - use tower::ServiceExt; - let bytes = serde_json::to_vec(&body).unwrap(); - let response = crate::router::build_router(Arc::clone(&f.state)) - .oneshot( - axum::http::Request::builder() - .method("POST") - .uri(path) - .header("host", &f.host) - .header("content-type", "application/json") - .header("authorization", authorization(f, keys, path, &bytes)) - .body(axum::body::Body::from(bytes)) - .unwrap(), - ) - .await - .unwrap(); - let status = response.status(); - let bytes = axum::body::to_bytes(response.into_body(), 8 * 1024 * 1024) - .await - .unwrap(); - (status, serde_json::from_slice(&bytes).unwrap()) -} -fn policy(f: &Fixture, policy: &str, prev: Option<&Event>) -> Event { - EventBuilder::new(Kind::Custom(9034), "") - .tags([ - Tag::parse(["community", &f.community.to_string()]).unwrap(), - Tag::parse(["type", "example.settings"]).unwrap(), - Tag::parse(["policy", policy]).unwrap(), - Tag::parse([ - "prev", - &prev.map(|e| e.id.to_hex()).unwrap_or_else(|| "0".into()), - ]) - .unwrap(), - ]) - .sign_with_keys(&f.owner) - .unwrap() -} -async fn accepted(f: &Fixture, keys: &Keys, event: &Event) { - let (status, body) = signed(f, keys, "/events", json!(event)).await; - assert!(status.is_success(), "{status}: {body}"); - assert_eq!(body["accepted"], true, "{body}"); -} - -#[tokio::test] -#[ignore = "requires Postgres and Redis"] -async fn signed_http_policy_replay_tenant_privacy_and_moderation() { - let f = fixture().await; - let d = Uuid::new_v4(); - let event = revision(&f, &f.peer, d, "create", None); - accepted(&f, &f.peer, &event).await; - let current = json!([{"artifact":"current","scope":"community","#type":["example.settings"]}]); - let (status, body) = signed(&f, &f.peer, "/query", current.clone()).await; - assert!(status.is_success(), "{status}: {body}"); - assert_eq!(body[0]["id"], event.id.to_hex()); - for (ids, expected) in [ - (vec![d.simple().to_string()], json!([])), - ( - vec![Uuid::new_v4().to_string(), d.to_string()], - json!([event]), - ), - ] { - let filter = json!([{"artifact":"history","scope":"community","#d":ids}]); - let (status, body) = signed(&f, &f.peer, "/query", filter).await; - assert_eq!(status, StatusCode::OK, "{body}"); - assert_eq!(body, expected); - } - assert!( - !f.request_as(&f.peer, "/query", current.clone()) - .await - .0 - .is_success(), - "unsigned dev header cannot read" - ); - for query in [ - json!([{"kinds":[45010]}]), - json!([{"ids":[event.id.to_hex()]}]), - json!([{"kinds":[45010],"search":"needle"}]), - json!([{"artifact":"current"}]), - json!([{"artifact":"history","#d":[d]}]), - ] { - let (status, body) = signed(&f, &f.peer, "/query", query).await; - assert!(status.is_success(), "{status}: {body}"); - assert_eq!(body, json!([])); - } - let (status, body) = signed(&f, &f.peer, "/count", json!([{"kinds":[45010]}])).await; - assert!(status.is_success(), "{status}: {body}"); - assert_eq!(body["count"], 0); - for path in ["/count"] { - assert!(!signed(&f, &f.peer, path, current.clone()) - .await - .0 - .is_success()); - } - for query in [ - json!([{"artifact":"incremental","scope":"community","query":{"artifact":"current"}}]), - json!([{"artifact":"incremental","query":{"artifact":"current","scope":"community"}}]), - ] { - assert!(!signed(&f, &f.peer, "/query", query).await.0.is_success()); - } - let command = policy(&f, "admins", None); - accepted(&f, &f.owner, &command).await; - accepted(&f, &f.owner, &command).await; - let audits: i64 = - sqlx::query_scalar("SELECT count(*) FROM audit_log WHERE community_id=$1 AND object_id=$2") - .bind(f.community.as_uuid()) - .bind(command.id.to_hex()) - .fetch_one(&f.pool) - .await - .unwrap(); - assert_eq!(audits, 1); - let (status, body) = signed( - &f, - &f.peer, - "/query", - json!([{"artifact":"policy","scope":"community","#type":["example.settings"]}]), - ) - .await; - assert!(status.is_success(), "{status}: {body}"); - assert_eq!( - body, - json!({"policy":"admins","revision":command.id.to_hex()}) - ); - accepted(&f, &f.peer, &event).await; // An acknowledgement cannot authorize a new edit. - let update = revision(&f, &f.peer, d, "update", Some(&event)); - assert!(!signed(&f, &f.peer, "/events", json!(update)) - .await - .0 - .is_success()); - let wrong_host = format!("other-{}.example", Uuid::new_v4()); - let wrong = f - .state - .db - .ensure_configured_community(&wrong_host) - .await - .unwrap() - .id; - sqlx::query("INSERT INTO relay_members(community_id,pubkey,role) VALUES($1,$2,'owner')") - .bind(wrong.as_uuid()) - .bind(f.owner.public_key().to_hex()) - .execute(&f.pool) - .await - .unwrap(); - let mut wrong_f = Fixture { - state: Arc::clone(&f.state), - pool: f.pool.clone(), - host: wrong_host, - community: wrong, - home: f.home, - private: f.private, - owner: f.owner.clone(), - peer: f.peer.clone(), - }; - for (keys, target) in [(&f.owner, &command), (&f.peer, &event)] { - let (status, body) = signed(&wrong_f, keys, "/events", json!(target)).await; - assert!(!status.is_success(), "{body}"); - } - wrong_f.host = f.host.clone(); // Reuse only for malformed scope controls below. - // Authority precedes target-specific refusal. A protected community - // revision and an unknown ID must have the same kind-5 response. - let mut refusals = Vec::new(); - for target in [event.id, nostr::EventId::from_byte_array([0xab; 32])] { - let deletion = EventBuilder::new(Kind::Custom(5), "") - .tags([Tag::event(target)]) - .sign_with_keys(&f.owner) - .unwrap(); - let response = signed(&f, &f.owner, "/events", json!(deletion)).await; - assert!(!response.0.is_success()); - refusals.push((response.0, response.1["error"].clone())); - } - assert_eq!(refusals[0], refusals[1]); - for path in ["/query", "/count"] { - assert_eq!( - signed(&f, &f.peer, path, json!([{ "scope":"community" }])) - .await - .0, - StatusCode::BAD_REQUEST - ); - } - let moderation = EventBuilder::new(Kind::Custom(9005), "") - .tags([ - Tag::parse(["community", &f.community.to_string()]).unwrap(), - Tag::event(event.id), - ]) - .sign_with_keys(&f.owner) - .unwrap(); - accepted(&f, &f.owner, &moderation).await; - let (_, body) = signed(&f, &f.peer, "/query", current.clone()).await; - assert_eq!(body, json!([])); - accepted(&f, &f.peer, &event).await; // Ledger receipt survives redaction. - sqlx::query( - "INSERT INTO community_bans(community_id,pubkey,actor_pubkey,banned) VALUES($1,$2,$3,true)", - ) - .bind(f.community.as_uuid()) - .bind(f.peer.public_key().as_bytes().as_slice()) - .bind(f.owner.public_key().as_bytes().as_slice()) - .execute(&f.pool) - .await - .unwrap(); - assert!(!signed(&f, &f.peer, "/events", json!(event)) - .await - .0 - .is_success()); - assert!(!signed(&f, &f.peer, "/query", current).await.0.is_success()); -} - -#[tokio::test] -#[ignore = "requires Postgres and Redis"] -async fn policy_command_preserves_relay_admin_timeout_and_ban_rules() { - let f = fixture().await; - let command = policy(&f, "admins", None); - accepted(&f, &f.owner, &command).await; - let next = policy(&f, "everyone", Some(&command)); - sqlx::query("INSERT INTO community_bans(community_id,pubkey,actor_pubkey,muted_until) VALUES($1,$2,$2,clock_timestamp()+interval '5 minutes')") - .bind(f.community.as_uuid()) - .bind(f.owner.public_key().as_bytes().as_slice()) - .execute(&f.pool) - .await - .unwrap(); - f.state.invalidate_restrictions_local(f.community); - for event in [&next, &command] { - let (status, body) = signed(&f, &f.owner, "/events", json!(event)).await; - assert_eq!(status, StatusCode::FORBIDDEN, "{body}"); - assert!( - body["error"] - .as_str() - .unwrap() - .starts_with("restricted: you are timed out"), - "{body}" - ); - } - let read = json!([{"artifact":"policy","scope":"community","#type":["example.settings"]}]); - let (status, body) = signed(&f, &f.owner, "/query", read).await; - assert_eq!(status, StatusCode::OK, "{body}"); - assert_eq!( - body, - json!({"policy":"admins","revision":command.id.to_hex()}) - ); - let content = revision(&f, &f.owner, Uuid::new_v4(), "create", None); - assert!(!signed(&f, &f.owner, "/events", json!(content)) - .await - .0 - .is_success()); - sqlx::query( - "UPDATE community_bans SET banned=true,muted_until=NULL WHERE community_id=$1 AND pubkey=$2", - ) - .bind(f.community.as_uuid()) - .bind(f.owner.public_key().as_bytes().as_slice()) - .execute(&f.pool) - .await - .unwrap(); - f.state.invalidate_restrictions_local(f.community); - assert!(!signed(&f, &f.owner, "/events", json!(command)) - .await - .0 - .is_success()); -} - -/// Seed an unsupported legacy event-store row to prove privacy fences before -/// SQL LIMIT/rank/count and raw hydration, even with the feature switch off. -#[tokio::test] -#[ignore = "requires Postgres and Redis"] -async fn ordinary_apis_withhold_unexpected_community_event_rows() { - let mut f = Fixture::new().await; - Arc::make_mut(&mut Arc::get_mut(&mut f.state).unwrap().config).community_artifacts_enabled = - false; - let event = revision(&f, &f.owner, Uuid::new_v4(), "create", None); - f.state - .db - .insert_event(f.community, &event, Some(f.home)) - .await - .unwrap(); - for query in [ - json!([{"kinds":[45010]}]), - json!([{"ids":[event.id.to_hex()]}]), - json!([{"kinds":[45010],"search":"needle"}]), - json!([{"artifact":"history","#d":[event.tags.identifier().unwrap()]}]), - ] { - let (status, body) = signed(&f, &f.owner, "/query", query).await; - assert!(status.is_success(), "{status}: {body}"); - assert_eq!(body, json!([])); - } - let (_, body) = signed(&f, &f.owner, "/count", json!([{"kinds":[45010]}])).await; - assert_eq!(body["count"], 0); - assert!(f - .state - .db - .get_event_by_id(f.community, event.id.as_bytes()) - .await - .unwrap() - .is_none()); - let stored = buzz_core::StoredEvent::new(event, Some(f.home)); - let recipient = (Uuid::new_v4(), "ordinary".into()); - assert!(crate::handlers::event::filter_fanout_by_access( - &f.state, - f.community, - &stored, - vec![recipient.clone()], - None - ) - .await - .is_empty()); - assert!(crate::handlers::event::route_fanout_matches( - &f.state, - f.community, - &stored, - vec![recipient], - None - ) - .await - .is_empty()); -} - -#[tokio::test] -#[ignore = "requires Postgres and Redis"] -async fn channel_artifact_with_community_tag_value_remains_visible() { - use crate::handlers::group_state_postgres_tests::{req_event_ids, test_conn}; - - let mut f = Fixture::new().await; - Arc::make_mut(&mut Arc::get_mut(&mut f.state).unwrap().config).community_artifacts_enabled = - false; - let d = Uuid::new_v4(); - let event = f.revision(d, "create", None); - let event = resign( - &event, - &f.owner, - &[["project", "community"]], - event.created_at.as_secs(), - ); - f.publish(&event).await; - let id = event.id.to_hex(); - let filter = json!({"kinds":[45010],"#h":[f.home]}); - - for read in [ - filter.clone(), - json!({"ids":[id]}), - json!({"artifact":"current","#d":[d]}), - json!({"artifact":"history","#d":[d]}), - json!({"kinds":[45010],"#h":[f.home],"search":"searchable"}), - ] { - let (status, body) = f.request("/query", json!([read])).await; - assert!(status.is_success(), "{read}: {status} {body}"); - assert_eq!(body.as_array().unwrap().len(), 1, "{read}: {body}"); - assert_eq!(body[0]["id"], id, "{read}: {body}"); - } - let (status, body) = f.request("/count", json!([filter])).await; - assert!(status.is_success(), "{status}: {body}"); - assert_eq!(body["count"], 1, "{body}"); - - let tenant = crate::tenant::bind_community(&f.state.db, &f.host) - .await - .unwrap(); - assert_eq!( - req_event_ids(&f.state, &tenant, &f.owner, filter.clone()).await, - std::slice::from_ref(&id) - ); - let (conn, mut rx) = test_conn(&tenant, &f.owner); - let filter = serde_json::from_value(filter).unwrap(); - crate::handlers::count::handle_count("c".into(), vec![filter], conn, f.state.clone()).await; - let axum::extract::ws::Message::Text(frame) = rx.try_recv().expect("COUNT reply") else { - panic!("expected a WebSocket text frame"); - }; - let message: Value = serde_json::from_str(&frame).unwrap(); - assert_eq!(message, json!(["COUNT", "c", {"count":1}])); - - let db = &f.state.db; - let bytes = event.id.as_bytes(); - assert_eq!( - db.get_event_by_id(f.community, bytes) - .await - .unwrap() - .map(|stored| stored.event.id), - Some(event.id) - ); - assert_eq!( - db.get_event_by_id_including_deleted(f.community, bytes) - .await - .unwrap() - .map(|stored| stored.event.id), - Some(event.id) - ); - assert_eq!( - db.admin_get_event_preview(*f.community.as_uuid(), bytes) - .await - .unwrap() - .map(|preview| preview.id), - Some(id) - ); -} - -/// The production policy command must roll back its CAS if its hash-chain -/// audit cannot persist, and the exact command can then be retried. -#[tokio::test] -#[ignore = "requires Postgres and Redis"] -async fn policy_audit_failure_rolls_back_cas_and_retry_keeps_chain_valid() { - let f = fixture().await; - let command = policy(&f, "admins", None); - sqlx::query("ALTER TABLE audit_log ADD CONSTRAINT probe_audit_failure CHECK (false) NOT VALID") - .execute(&f.pool) - .await - .unwrap(); - let (status, _) = signed(&f, &f.owner, "/events", json!(command)).await; - assert!(!status.is_success()); - let state: Value = - sqlx::query_scalar("SELECT artifact_type_policies FROM communities WHERE id=$1") - .bind(f.community.as_uuid()) - .fetch_one(&f.pool) - .await - .unwrap(); - assert_eq!(state, json!({})); - sqlx::query("ALTER TABLE audit_log DROP CONSTRAINT probe_audit_failure") - .execute(&f.pool) - .await - .unwrap(); - accepted(&f, &f.owner, &command).await; - accepted(&f, &f.owner, &command).await; - let count: i64 = - sqlx::query_scalar("SELECT count(*) FROM audit_log WHERE community_id=$1 AND object_id=$2") - .bind(f.community.as_uuid()) - .bind(command.id.to_hex()) - .fetch_one(&f.pool) - .await - .unwrap(); - assert_eq!(count, 1); - assert!(buzz_audit::AuditService::new(f.pool.clone()) - .verify_chain(f.community, 1, i64::MAX) - .await - .unwrap()); -} diff --git a/crates/buzz-relay/src/api/artifact_sync.rs b/crates/buzz-relay/src/api/artifact_sync.rs index f0c6eab8427..8b50f748939 100644 --- a/crates/buzz-relay/src/api/artifact_sync.rs +++ b/crates/buzz-relay/src/api/artifact_sync.rs @@ -151,9 +151,7 @@ async fn execute( let query_binding = URL_SAFE_NO_PAD.encode(Sha256::digest( serde_json::to_vec(&request.query).map_err(|_| invalid())?, )); - if parsed.view != ArtifactView::Current - || parsed.scope != buzz_core::artifact::ArtifactScope::Channel - { + if parsed.view != ArtifactView::Current { return Err(invalid()); } let (now, policy) = state diff --git a/crates/buzz-relay/src/api/bridge.rs b/crates/buzz-relay/src/api/bridge.rs index ac98ad4648f..09909496174 100644 --- a/crates/buzz-relay/src/api/bridge.rs +++ b/crates/buzz-relay/src/api/bridge.rs @@ -109,8 +109,6 @@ pub(crate) struct ProvenCaller { pub(crate) signed_at: Option, /// The owner named by a verified agent token (Enforce only). pub(crate) token_owner: Option, - /// Owner proven by current membership admission for explicit artifact reads. - pub(crate) artifact_owner: Option, slot: AccessSlot, } @@ -130,7 +128,6 @@ impl ProvenCaller { event_id_bytes, signed_at, token_owner, - artifact_owner: None, slot: slot.clone(), } } @@ -1467,25 +1464,17 @@ async fn submit_event_authed( token_owner, ) .await; - let artifact_owner = match caller.admit_member(membership) { - Ok(owner) => owner.or(token_owner), - Err(e) => { - return SubmitOutcome::Err { - response: e.into_response(), - } - } - }; + if let Err(e) = caller.admit_member(membership) { + return SubmitOutcome::Err { + response: e.into_response(), + }; + } let auth = IngestAuth::Http { pubkey, scopes: buzz_auth::Scope::all_known(), // Pure Nostr: full scopes, channel access via membership - auth_method: if signed_auth_created_at.is_some() { - crate::handlers::ingest::HttpAuthMethod::Nip98 - } else { - crate::handlers::ingest::HttpAuthMethod::DevPubkey - }, - } - .with_verified_owner(artifact_owner); + auth_method: crate::handlers::ingest::HttpAuthMethod::Nip98, + }; // Typing indicators are ephemeral: broadcast to the channel, never stored. let result = if is_typing { @@ -1635,9 +1624,8 @@ pub async fn query_events( // This authority surface always needs payload-bound NIP-98, including dev. // Detect before admission, and before Filter can drop the extension key. - let compact_membership = serde_json::from_slice::>(&body).is_ok_and(|filters| { - membership_snapshot::requested(&filters) || filters.iter().any(|f| f.get("scope").is_some()) - }); + let compact_membership = serde_json::from_slice::>(&body) + .is_ok_and(|filters| membership_snapshot::requested(&filters)); // NIP-FI admission. [FI-TRACE-AUTHORITY-UNIFORM] let proof = crate::nip_fi_shadow::EnforcedProof::new(&state, &headers, "bridge"); @@ -1711,7 +1699,7 @@ async fn query_events_authed( caller.token_owner, ) .await; - caller.artifact_owner = caller + caller .admit_member(membership) .map_err(IntoResponse::into_response)?; @@ -1746,7 +1734,7 @@ async fn query_member_events( } let routed = || caller.read_artifact(&raw_filters); if let Some(result) = - super::artifact::query(state, tenant, caller, &raw_filters, false, routed).await + super::artifact::query(state, tenant, &pubkey, &raw_filters, false, routed).await { return result; } @@ -2409,7 +2397,7 @@ async fn count_events_authed( caller.token_owner, ) .await; - caller.artifact_owner = caller + caller .admit_member(membership) .map_err(IntoResponse::into_response)?; @@ -2430,7 +2418,7 @@ async fn count_member_events( let raw: Vec = serde_json::from_slice(body) .map_err(|e| api_error(StatusCode::BAD_REQUEST, &format!("invalid filters: {e}")))?; let routed = || caller.read_artifact(&raw); - if let Some(result) = super::artifact::query(state, tenant, caller, &raw, true, routed).await { + if let Some(result) = super::artifact::query(state, tenant, &pubkey, &raw, true, routed).await { return result; } let filters: Vec = serde_json::from_slice(body) @@ -3506,7 +3494,6 @@ pub(crate) mod postgres_tests { event_id_bytes: fresh_nip98_event_id_bytes(), signed_at: None, token_owner: None, - artifact_owner: None, slot: AccessSlot::default(), }; caller.read_artifact(&raw); @@ -11327,7 +11314,6 @@ pub(crate) mod postgres_tests { event_id_bytes: fresh_nip98_event_id_bytes(), signed_at: Some(nostr::Timestamp::now().as_secs()), token_owner: None, - artifact_owner: None, slot: AccessSlot::default(), }, None, @@ -11507,7 +11493,6 @@ pub(crate) mod postgres_tests { event_id_bytes: fresh_nip98_event_id_bytes(), signed_at: Some(nostr::Timestamp::now().as_secs()), token_owner: None, - artifact_owner: None, slot: AccessSlot::default(), }, None, diff --git a/crates/buzz-relay/src/config.rs b/crates/buzz-relay/src/config.rs index e6be69d5bc2..4f91dfa75b2 100644 --- a/crates/buzz-relay/src/config.rs +++ b/crates/buzz-relay/src/config.rs @@ -185,8 +185,6 @@ pub struct Config { pub require_auth_token: bool, /// Opt-in private accessory API; disabled until explicitly deployed. pub buzz_v1_enabled: bool, - /// Activate NIP-AR community storage only after the operator schema contract. - pub community_artifacts_enabled: bool, /// Opt-in NIP-CL compact membership projection; dark by default. pub membership_snapshot_enabled: bool, /// Opt-in NIP-CL public memberships, independent of self discovery. @@ -1550,16 +1548,6 @@ impl Config { auth, require_auth_token, buzz_v1_enabled, - community_artifacts_enabled: match std::env::var("BUZZ_COMMUNITY_ARTIFACTS_ENABLED") { - Err(std::env::VarError::NotPresent) => false, - Ok(v) if v == "true" => true, - Ok(v) if v == "false" => false, - _ => { - return Err(ConfigError::InvalidValue( - "BUZZ_COMMUNITY_ARTIFACTS_ENABLED must be true or false".into(), - )) - } - }, membership_snapshot_enabled: std::env::var("BUZZ_MEMBERSHIP_SNAPSHOT_ENABLED") .is_ok_and(|v| v == "true"), membership_public_enabled: std::env::var("BUZZ_MEMBERSHIP_PUBLIC_ENABLED") diff --git a/crates/buzz-relay/src/handlers/artifact.rs b/crates/buzz-relay/src/handlers/artifact.rs index 0e7fc023f94..c52e71d6d4d 100644 --- a/crates/buzz-relay/src/handlers/artifact.rs +++ b/crates/buzz-relay/src/handlers/artifact.rs @@ -47,27 +47,25 @@ pub(crate) async fn accept( ) .await .map_err(|e| IngestError::Internal(format!("artifact storage: {e}")))?; - for stored in accepted_events(outcome)? { - publish(state, tenant, &stored).await; - } - Ok(IngestResult { - event_id: event.id.to_hex(), - accepted: true, - message: String::new(), - }) -} - -pub(super) fn accepted_events(outcome: ArtifactOutcome) -> Result, IngestError> { match outcome { - ArtifactOutcome::Accepted(events) => Ok(events), - ArtifactOutcome::Duplicate => Ok(Vec::new()), + ArtifactOutcome::Accepted(events) => { + for stored in &events { + publish(state, tenant, stored).await; + } + } + ArtifactOutcome::Duplicate => {} ArtifactOutcome::Conflict(message) => { - Err(IngestError::CanvasConflict(format!("conflict: {message}"))) + return Err(IngestError::CanvasConflict(format!("conflict: {message}"))) } ArtifactOutcome::Rejected(message) => { - Err(IngestError::Rejected(format!("invalid: {message}"))) + return Err(IngestError::Rejected(format!("invalid: {message}"))) } } + Ok(IngestResult { + event_id: event.id.to_hex(), + accepted: true, + message: String::new(), + }) } fn head_unavailable() -> IngestError { @@ -90,7 +88,7 @@ async fn publish(state: &Arc, tenant: &TenantContext, stored: &StoredE super::event::fan_out_event_to_local_subscribers(state, tenant.community(), stored).await; } -pub(super) fn verify_revision_auth(event: &Event) -> Result<(), IngestError> { +fn verify_revision_auth(event: &Event) -> Result<(), IngestError> { for tag in event.tags.iter().filter(|t| t.as_slice()[0] == "auth") { let json = serde_json::to_string(tag.as_slice()) .map_err(|e| IngestError::Internal(e.to_string()))?; diff --git a/crates/buzz-relay/src/handlers/artifact_sync.rs b/crates/buzz-relay/src/handlers/artifact_sync.rs index 0a2bc3d20c1..fa0cadf57e2 100644 --- a/crates/buzz-relay/src/handlers/artifact_sync.rs +++ b/crates/buzz-relay/src/handlers/artifact_sync.rs @@ -11,8 +11,7 @@ use std::time::Duration; use axum::extract::ws::Message as WsMessage; use buzz_auth::Scope; use buzz_core::artifact_sync::{ArtifactSyncFilter, MAX_SYNC_EVENTS}; -use buzz_core::{artifact::ArtifactScope, CommunityId, StoredEvent}; -use buzz_db::community_artifact::CommunityArtifactPrincipal; +use buzz_core::StoredEvent; use buzz_pubsub::EventTopic; use dashmap::DashMap; use nostr::{Alphabet, Event, Filter, JsonUtil, Kind, SingleLetterTag}; @@ -103,17 +102,9 @@ fn artifact_id(event: &Event) -> Option { .and_then(|tag| tag.as_slice().get(1)?.parse().ok()) } -struct CommunityInterest { - tenant: CommunityId, - artifact_type: String, - identities: Option>, - principal: CommunityArtifactPrincipal, -} - /// One live sync's signal inbox. Fan-out and loss detection write to it; the /// sync's own task is its only reader. pub struct SyncHandle { - community: Option, pending: StdMutex, notify: Notify, cancel: CancellationToken, @@ -122,7 +113,6 @@ pub struct SyncHandle { impl SyncHandle { fn new() -> Self { Self { - community: None, pending: StdMutex::new(Pending::default()), notify: Notify::new(), cancel: CancellationToken::new(), @@ -204,55 +194,6 @@ impl ArtifactSyncs { }); } - /// Route metadata only to the same tenant and immutable type. Historical - /// redactions never produce a signal; current redactions retire exact copies. - pub(crate) fn signal_community( - &self, - community: CommunityId, - signal: &buzz_pubsub::artifact_signal::ArtifactSignal, - ) { - for entry in self.syncs.iter() { - let Some(interest) = &entry.community else { - continue; - }; - if interest.tenant != community - || interest.artifact_type != signal.artifact_type - || interest - .identities - .as_ref() - .is_some_and(|ids| !ids.contains(&signal.d)) - { - continue; - } - if signal.cause == buzz_pubsub::artifact_signal::ArtifactChange::Redacted { - entry.resync("resync: redaction"); - } else { - entry.update(|pending| pending.hold(signal.d, None)); - } - } - } - /// Admission changes invalidate idle community syncs on every receiving pod. - pub(crate) fn resync_community(&self, community: CommunityId) { - for entry in self.syncs.iter() { - if entry - .community - .as_ref() - .is_some_and(|i| i.tenant == community) - { - entry.resync("resync: community access changed"); - } - } - } - - /// End exactly the syncs that read from the community signal receiver. - fn resync_community_interests(&self, reason: &'static str) { - for entry in self.syncs.iter() { - if entry.community.is_some() { - entry.resync(reason); - } - } - } - /// End every sync on this node: a loss here can affect any of them. pub fn resync_all(&self, reason: &'static str) { for entry in self.syncs.iter() { @@ -330,27 +271,6 @@ impl ArtifactSyncs { } } -/// Consume typed metadata from the existing Redis subscriber. A gap in this -/// receiver can only affect community syncs. -pub fn spawn_signals(state: Arc) -> tokio::task::JoinHandle<()> { - let mut rx = state.pubsub.subscribe_artifacts(); - tokio::spawn(async move { - loop { - tokio::select! { - () = state.community_revalidator_cancel.cancelled() => return, - result = rx.recv() => match result { - Ok(scoped) => state.artifact_syncs.signal_community(scoped.community_id, &scoped.signal), - Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => state.artifact_syncs.resync_community_interests("resync: live delivery lagged"), - Err(tokio::sync::broadcast::error::RecvError::Closed) => { - state.artifact_syncs.resync_community_interests("resync: live delivery interrupted"); - return; - } - } - } - } - }) -} - /// Resync every sync on this node whenever its Redis link may have lost a /// message (rule 5). A sync records the epoch its interest was confirmed on, /// so any later change reaches it here. Runs until the link owner stops. @@ -462,11 +382,9 @@ pub async fn handle_sync( }; // Written when the initial set ends, not when live delivery does. let mut access = ReadLog::sync(&conn, &sub_id, &filter.channels); - let (reader, bound, delegated_owner) = match conn.auth_state_snapshot() { + let (reader, bound) = match conn.auth_state_snapshot() { AuthState::Authenticated(ctx) => { - if (filter.scope == ArtifactScope::Community || !ctx.scopes.is_empty()) - && !ctx.scopes.contains(&Scope::MessagesRead) - { + if !ctx.scopes.is_empty() && !ctx.scopes.contains(&Scope::MessagesRead) { super::close::close_if_owner( &sub_id, owner, @@ -481,20 +399,14 @@ pub async fn handle_sync( // A channel-scoped token reaches only its own channels; outside // them the answer matches an unreadable channel. if let Some(allowed) = ctx.channel_ids.as_deref() { - if filter.scope == ArtifactScope::Community - || filter.channels.iter().any(|id| !allowed.contains(id)) - { + if filter.channels.iter().any(|id| !allowed.contains(id)) { super::close::close_if_owner(&sub_id, owner, Some(RESTRICTED), &conn, &state) .await; access.deny("not_channel_member"); return; } } - ( - ctx.pubkey.to_bytes().to_vec(), - ctx.channel_ids, - ctx.agent_owner_pubkey, - ) + (ctx.pubkey.to_bytes().to_vec(), ctx.channel_ids) } _ => { super::close::close_if_owner( @@ -527,63 +439,11 @@ pub async fn handle_sync( // Rule 1: live interest first, confirmed by Redis on an unbroken link. let start = *state.pubsub.link_state().borrow(); - let mut handle = SyncHandle::new(); - if filter.scope == ArtifactScope::Community { - if !super::community_artifact::enabled(&state) - .await - .unwrap_or(false) - { - close( - &sub_id, - owner, - "error: community artifacts unavailable", - &conn, - &state, - ) - .await; - return; - } - let mode = state.config.nip_fi.mode; - let has_fi = conn.nip_fi_assertion.is_some(); - if mode.denies_unconditionally() || (mode.enforces() && !has_fi) { - close( - &sub_id, - owner, - "restricted: authorization denied", - &conn, - &state, - ) - .await; - return; - } - handle.community = Some(CommunityInterest { - tenant: conn.tenant.community(), - artifact_type: buzz_core::artifact::exact_type(&filter.tags) - .unwrap_or_default() - .into(), - identities: filter - .tags - .iter() - .find(|(name, _)| name == "d") - .map(|(_, values)| values.iter().filter_map(|v| v.parse().ok()).collect()), - principal: CommunityArtifactPrincipal { - owner_admission: super::community_artifact::owner_admission( - &state, - &conn, - delegated_owner, - ), - pubkey: reader.clone(), - verified_owner: delegated_owner.map(|p| p.to_bytes().to_vec()), - require_membership: state.config.require_relay_membership, - reject_required_nip_fi: mode.with_requirement(true).enforces() && !has_fi, - }, - }); - } - let handle = Arc::new(handle); - let Some(owner) = claim(&sub_id, owner, &filter, &handle, &conn, &state).await else { + let handle = Arc::new(SyncHandle::new()); + let Some(owner) = claim(&sub_id, owner, &filter.channels, &handle, &conn, &state).await else { return; }; - if !start.up || !confirm(&filter, start.epoch, &conn, &state).await { + if !start.up || !confirm(&filter.channels, start.epoch, &conn, &state).await { close( &sub_id, owner, @@ -600,19 +460,10 @@ pub async fn handle_sync( // time budget and the cancellation race, so a slow reader cannot hold // the handler slot past the budget or get EOSE after retirement. let initial = async { - let sent = send_initial_set( - &sub_id, - owner, - &filter, - &reader, - &mut access, - &conn, - &state, - &handle, - ) - .await?; + let sent = + send_initial_set(&sub_id, owner, &filter, &reader, &mut access, &conn, &state).await?; // A resync requested before EOSE is queued ends the sync without it. - send_eose(&sub_id, owner, &handle, &conn, Some(&state)).await?; + send_eose(&sub_id, owner, &handle, &conn).await?; Ok::<_, Stop>(sent) }; let outcome = tokio::select! { @@ -684,7 +535,7 @@ enum Stop { async fn claim( sub_id: &str, owner: u64, - filter: &ArtifactSyncFilter, + channels: &[Uuid], handle: &Arc, conn: &ConnectionState, state: &AppState, @@ -697,23 +548,6 @@ async fn claim( state .artifact_syncs .insert(conn.conn_id, sub_id, Arc::clone(handle)); - let channels = &filter.channels; - if filter.scope == ArtifactScope::Community { - state.sub_registry.register_filters_scoped( - conn.tenant.community(), - conn.conn_id, - sub_id.to_owned(), - vec![( - Filter::new(), - crate::subscription::SubscriptionScope::community_artifacts(), - )], - ); - state - .pubsub - .retain_topic(&conn.tenant, EventTopic::CommunityArtifact) - .await; - return Some(owner); - } state.sub_registry.register_channels_scoped( conn.tenant.community(), conn.conn_id, @@ -732,17 +566,9 @@ async fn claim( /// Wait until Redis confirms every channel topic on link epoch `epoch`. A /// later change of the epoch resyncs this sync through `resync_all`. -async fn confirm( - filter: &ArtifactSyncFilter, - epoch: u64, - conn: &ConnectionState, - state: &AppState, -) -> bool { +async fn confirm(channels: &[Uuid], epoch: u64, conn: &ConnectionState, state: &AppState) -> bool { let confirm_all = async { - if filter.scope == ArtifactScope::Community { - return matches!(state.pubsub.confirm_topic(&conn.tenant,EventTopic::CommunityArtifact).await,Ok(confirmed) if confirmed==epoch); - } - for &channel in &filter.channels { + for &channel in channels { match state .pubsub .confirm_topic(&conn.tenant, EventTopic::Channel(channel)) @@ -761,7 +587,6 @@ async fn confirm( /// Read and send every head in scope from one snapshot, and return their /// `d`. After an `Err` nothing more is sent. -#[allow(clippy::too_many_arguments)] async fn send_initial_set( sub_id: &str, owner: u64, @@ -770,33 +595,17 @@ async fn send_initial_set( access: &mut ReadLog, conn: &ConnectionState, state: &AppState, - handle: &SyncHandle, ) -> Result, Stop> { - let mut snapshot = if let Some(interest) = &handle.community { - match state - .db - .open_community_artifact_snapshot(conn.tenant.community(), &interest.principal) - .await - { - Ok(snapshot) => snapshot, - Err(buzz_db::DbError::AccessDenied(_)) => return Err(Stop::Close(RESTRICTED)), - Err(e) => { - warn!(conn_id = %conn.conn_id, error_kind = %e.kind(), "artifact sync snapshot failed"); - return Err(Stop::Close(READ_FAILED)); - } - } - } else { - match state - .db - .open_artifact_snapshot(conn.tenant.community(), reader, &filter.channels) - .await - { - Ok(Ok(snapshot)) => snapshot, - Ok(Err(buzz_db::SnapshotDenied::Restricted)) => return Err(Stop::Close(RESTRICTED)), - Err(e) => { - warn!(conn_id = %conn.conn_id, error_kind = %e.kind(), "artifact sync snapshot failed"); - return Err(Stop::Close(READ_FAILED)); - } + let mut snapshot = match state + .db + .open_artifact_snapshot(conn.tenant.community(), reader, &filter.channels) + .await + { + Ok(Ok(snapshot)) => snapshot, + Ok(Err(buzz_db::SnapshotDenied::Restricted)) => return Err(Stop::Close(RESTRICTED)), + Err(e) => { + warn!(conn_id = %conn.conn_id, error_kind = %e.kind(), "artifact sync snapshot failed"); + return Err(Stop::Close(READ_FAILED)); } }; let mut sent = HashSet::new(); @@ -821,8 +630,6 @@ async fn send_initial_set( owner, RelayMessage::event(sub_id, &stored.event), conn, - Some(handle), - Some(state), ) .await?; access.queued_one(); @@ -845,10 +652,8 @@ async fn send_owned( owner: u64, frame: String, conn: &ConnectionState, - handle: Option<&SyncHandle>, - state: Option<&AppState>, ) -> Result<(), Stop> { - send_reserved(sub_id, owner, frame, handle, conn, state).await + send_reserved(sub_id, owner, frame, None, conn).await } /// Queue `EOSE` like `send_owned`, unless the sync must resync. The pending @@ -860,7 +665,6 @@ async fn send_eose( owner: u64, handle: &SyncHandle, conn: &ConnectionState, - state: Option<&AppState>, ) -> Result<(), Stop> { send_reserved( sub_id, @@ -868,7 +672,6 @@ async fn send_eose( RelayMessage::eose(sub_id), Some(handle), conn, - state, ) .await } @@ -879,18 +682,14 @@ async fn send_reserved( frame: String, unless_resync: Option<&SyncHandle>, conn: &ConnectionState, - state: Option<&AppState>, ) -> Result<(), Stop> { let slot = conn .send_tx .reserve() .await .map_err(|_| Stop::Close("error: connection closed"))?; - #[cfg(test)] - super::close::test_seam::pause_at(&test_seam::QUEUE_CHECK_PAUSE).await; - let _effect = community_queue_effect(unless_resync, state, conn).await?; let subs = conn.subscriptions.lock().await; - if conn.cancel.is_cancelled() || !super::close::owns(&subs, sub_id, owner) { + if !super::close::owns(&subs, sub_id, owner) { return Err(Stop::Retired); } let pending = unless_resync.map(|handle| { @@ -913,74 +712,16 @@ async fn try_send_owned( owner: u64, frame: String, conn: &ConnectionState, - handle: Option<&SyncHandle>, - state: Option<&AppState>, ) -> Result<(), Stop> { - let slot = conn - .send_tx - .try_reserve() - .map_err(|_| Stop::Close("resync: send queue full"))?; - let _effect = community_queue_effect(handle, state, conn).await?; let subs = conn.subscriptions.lock().await; - if conn.cancel.is_cancelled() || !super::close::owns(&subs, sub_id, owner) { + if !super::close::owns(&subs, sub_id, owner) { return Err(Stop::Retired); } - let pending = handle.map(|h| h.pending.lock().unwrap_or_else(PoisonError::into_inner)); - if let Some(reason) = pending.as_ref().and_then(|p| p.resync) { - return Err(Stop::Close(reason)); - } - slot.send(WsMessage::Text(frame.into())); - Ok(()) -} -/// Retain the socket credential gate through enqueue for community deliveries. -async fn community_queue_effect( - handle: Option<&SyncHandle>, - state: Option<&AppState>, - conn: &ConnectionState, -) -> Result, Stop> { - if conn.cancel.is_cancelled() || handle.is_some_and(|h| h.cancel.is_cancelled()) { - return Err(Stop::Retired); - } - let Some(interest) = handle.and_then(|h| h.community.as_ref()) else { - return Ok(None); - }; - let state = state.ok_or(Stop::Close("resync: access check unavailable"))?; - let effect = conn - .nip_fi_gate - .acquire_effect() - .await - .map_err(|_| Stop::Close("resync: community credential changed"))?; - if !community_credential_current(state, conn, &interest.principal) { - return Err(Stop::Close("resync: community access changed")); - } - Ok(Some(effect)) + conn.send_tx + .try_send(WsMessage::Text(frame.into())) + .map_err(|_| Stop::Close("resync: send queue full")) } -fn community_credential_current( - state: &AppState, - conn: &ConnectionState, - principal: &CommunityArtifactPrincipal, -) -> bool { - let AuthState::Authenticated(ctx) = conn.auth_state_snapshot() else { - return false; - }; - !conn.cancel.is_cancelled() - && conn - .session_deadline - .is_none_or(|deadline| deadline > chrono::Utc::now()) - && ctx.channel_ids.is_none() - && ctx.scopes.contains(&Scope::MessagesRead) - && ctx.pubkey.as_bytes().as_slice() == principal.pubkey - && ctx.agent_owner_pubkey.map(|p| p.to_bytes().to_vec()) == principal.verified_owner - && super::community_artifact::owner_admission(state, conn, ctx.agent_owner_pubkey) - == principal.owner_admission - && !conn.nip_fi_gate.is_expired_or_past_deadline() - && !conn.nip_fi_assertion.as_ref().is_some_and(|assertion| { - state.nip_fi_deny_map.as_deref().is_some_and(|map| { - crate::nip_fi_core::assertion_denied(map, assertion, chrono::Utc::now()) - }) - }) -} /// Rules 3–5 after `EOSE`: read each changed head, one read at a time, and /// send it. A dropped frame or a resync request ends the sync. `in_set` is /// the client's copy as this sync sent it: the `d` of each artifact in scope. @@ -1009,37 +750,19 @@ async fn run_live( if handle.cancel.is_cancelled() { return; } - let head_result = if let Some(interest) = &handle.community { - state - .db - .community_artifact_head(conn.tenant.community(), &interest.principal, d) - .await - } else { - state - .db - .artifact_head(conn.tenant.community(), reader, d, &filter.channels) - .await - }; - let head = match head_result { + let head = match state + .db + .artifact_head(conn.tenant.community(), reader, d, &filter.channels) + .await + { Ok(head) => head.filter(|(head, _)| { bound.is_none_or(|allowed| { head.channel_id.is_some_and(|id| allowed.contains(&id)) }) }), - Err(buzz_db::DbError::AccessDenied(_)) if handle.community.is_some() => { - close( - sub_id, - owner, - "resync: community access changed", - conn, - state, - ) - .await; - return; - } Err(e) => { warn!(conn_id = %conn.conn_id, error_kind = %e.kind(), "artifact sync head read failed"); - close(sub_id, owner, READ_FAILED, conn, state).await; + close(sub_id, owner, "error: sync read failed", conn, state).await; return; } }; @@ -1062,16 +785,7 @@ async fn run_live( }; #[cfg(test)] super::close::test_seam::pause_at(&test_seam::LIVE_SEND_PAUSE).await; - match try_send_owned( - sub_id, - owner, - RelayMessage::event(sub_id, &event), - conn, - Some(handle), - Some(state), - ) - .await - { + match try_send_owned(sub_id, owner, RelayMessage::event(sub_id, &event), conn).await { Ok(()) => {} Err(Stop::Retired) => return, // One lost frame breaks the copy; the slow-client grace limit @@ -1112,8 +826,6 @@ pub(crate) mod test_seam { tokio::task_local! { /// After a live head read, before its frame is queued. pub(crate) static LIVE_SEND_PAUSE: Arc; - /// After output reservation, before the current authorization guard. - pub(crate) static QUEUE_CHECK_PAUSE: Arc; } } @@ -1282,19 +994,17 @@ mod tests { async fn live_frame_is_fenced_by_the_owner() { let (conn, mut rx) = conn_with_sub(1); assert!(matches!( - try_send_owned("s", 2, "x".into(), &conn, None, None).await, + try_send_owned("s", 2, "x".into(), &conn).await, Err(Stop::Retired) )); conn.subscriptions.lock().await.remove("s"); assert!(matches!( - try_send_owned("s", 1, "x".into(), &conn, None, None).await, + try_send_owned("s", 1, "x".into(), &conn).await, Err(Stop::Retired) )); assert!(rx.try_recv().is_err()); conn.subscriptions.lock().await.insert("s".into(), held(1)); - assert!(try_send_owned("s", 1, "x".into(), &conn, None, None) - .await - .is_ok()); + assert!(try_send_owned("s", 1, "x".into(), &conn).await.is_ok()); assert!(rx.try_recv().is_ok()); } @@ -1310,7 +1020,7 @@ mod tests { .try_send(WsMessage::Text("fill".into())) .unwrap(); } - let mut waiting = std::pin::pin!(send_owned("s", 1, "eose".into(), &conn, None, None)); + let mut waiting = std::pin::pin!(send_owned("s", 1, "eose".into(), &conn)); // Polled once, the frame is now waiting in `reserve`. assert!(futures_util::poll!(&mut waiting).is_pending()); // A replacing REQ takes the ID while the frame waits. @@ -1338,7 +1048,7 @@ mod tests { .try_send(WsMessage::Text("fill".into())) .unwrap(); } - let mut waiting = std::pin::pin!(send_eose("s", 1, &handle, &conn, None)); + let mut waiting = std::pin::pin!(send_eose("s", 1, &handle, &conn)); assert!(futures_util::poll!(&mut waiting).is_pending()); // The held list overflows while EOSE waits. for _ in 0..=MAX_SYNC_EVENTS { @@ -1355,7 +1065,7 @@ mod tests { // Without a pending resync, EOSE is queued. let clean = SyncHandle::new(); - assert!(send_eose("s", 1, &clean, &conn, None).await.is_ok()); + assert!(send_eose("s", 1, &clean, &conn).await.is_ok()); let Ok(WsMessage::Text(text)) = rx.try_recv() else { panic!("no EOSE"); }; diff --git a/crates/buzz-relay/src/handlers/artifact_sync_postgres_tests.rs b/crates/buzz-relay/src/handlers/artifact_sync_postgres_tests.rs index e7d082f8cd9..9c8e3c5936c 100644 --- a/crates/buzz-relay/src/handlers/artifact_sync_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/artifact_sync_postgres_tests.rs @@ -691,5 +691,3 @@ async fn a_replaced_req_sends_nothing_under_a_sync_that_took_its_id() { .unwrap(); } } - -mod community_postgres_tests; diff --git a/crates/buzz-relay/src/handlers/artifact_sync_postgres_tests/community_postgres_tests.rs b/crates/buzz-relay/src/handlers/artifact_sync_postgres_tests/community_postgres_tests.rs deleted file mode 100644 index ade3d48e21b..00000000000 --- a/crates/buzz-relay/src/handlers/artifact_sync_postgres_tests/community_postgres_tests.rs +++ /dev/null @@ -1,817 +0,0 @@ -use super::*; -use crate::connection::AuthState; -use crate::handlers::ingest::{HttpAuthMethod, IngestAuth}; -use crate::handlers::{artifact_sync, close, event as event_handler}; -use buzz_auth::Scope; - -async fn community_fixture() -> Fixture { - let mut state = crate::api::bridge::postgres_tests::bridge_handler_test_state() - .await - .unwrap(); - let config = Arc::make_mut(&mut Arc::get_mut(&mut state).unwrap().config); - config.community_artifacts_enabled = true; - config.require_relay_membership = true; - let host = format!("community-sync-{}.example", Uuid::new_v4()); - let community = state - .db - .ensure_configured_community(&host) - .await - .unwrap() - .id; - let mut conn = state.db.pool().acquire().await.unwrap(); - sqlx::query( - "SET buzz.community_artifact_contract_ready='all-backends-enforce-community-audience'", - ) - .execute(&mut *conn) - .await - .unwrap(); - sqlx::raw_sql(include_str!( - "../../../../../scripts/maintenance/community-artifact-contract.sql" - )) - .execute(&mut *conn) - .await - .unwrap(); - drop(conn); - tokio::spawn(Arc::clone(&state.pubsub).run_subscriber()); - state - .pubsub - .link_state() - .wait_for(|link| link.up) - .await - .unwrap(); - Fixture { - state, - tenant: TenantContext::resolved(community, &host), - } -} -async fn member(f: &Fixture, keys: &Keys, role: &str) { - sqlx::query("INSERT INTO relay_members(community_id,pubkey,role) VALUES($1,$2,$3)") - .bind(f.tenant.community().as_uuid()) - .bind(keys.public_key().to_hex()) - .bind(role) - .execute(f.state.db.pool()) - .await - .unwrap(); -} -fn auth(keys: &Keys) -> IngestAuth { - IngestAuth::Http { - pubkey: keys.public_key(), - scopes: vec![Scope::MessagesWrite, Scope::MessagesRead, Scope::AdminUsers], - auth_method: HttpAuthMethod::Nip98, - } -} -fn signed_revision(f: &Fixture, keys: &Keys, d: Uuid, prev: Option<&Event>) -> Event { - let mut tags = vec![ - vec!["ar".into(), "1".into()], - vec!["community".into(), f.tenant.community().to_string()], - vec!["type".into(), "example.settings".into()], - vec!["d".into(), d.to_string()], - vec!["title".into(), "Settings".into()], - vec![ - "op".into(), - if prev.is_some() { - "update".into() - } else { - "create".into() - }, - ], - ]; - if let Some(prev) = prev { - tags.push(vec!["prev".into(), prev.id.to_hex()]); - } - EventBuilder::new(Kind::Custom(45010), "private snapshot") - .tags(tags.into_iter().map(|t| Tag::parse(t).unwrap())) - .sign_with_keys(keys) - .unwrap() -} -async fn revision(f: &Fixture, keys: &Keys, d: Uuid, prev: Option<&Event>) -> Event { - let event = signed_revision(f, keys, d, prev); - assert!( - ingest_event(&f.state, &f.tenant, event.clone(), auth(keys)) - .await - .unwrap() - .accepted - ); - event -} -fn connect(f: &Fixture, keys: &Keys) -> (Arc, mpsc::Receiver) { - let (conn, rx) = super::connect(f, keys); - if let AuthState::Authenticated(ctx) = &mut *conn.auth_state.lock().unwrap() { - ctx.scopes = vec![Scope::MessagesRead, Scope::MessagesWrite]; - } - (conn, rx) -} -fn filter() -> Value { - json!({"artifact":"current","scope":"community","#type":["example.settings"]}) -} -async fn remove(f: &Fixture, keys: &Keys) { - sqlx::query("DELETE FROM relay_members WHERE community_id=$1 AND pubkey=$2") - .bind(f.tenant.community().as_uuid()) - .bind(keys.public_key().to_hex()) - .execute(f.state.db.pool()) - .await - .unwrap(); -} -fn named_sync( - f: &Fixture, - conn: &Arc, - sub: &str, - filter: Value, -) -> tokio::task::JoinHandle<()> { - let sub = sub.to_owned(); - let filter = buzz_core::artifact_sync::parse_sync(&filter); - let permit = f - .state - .handler_semaphore - .clone() - .try_acquire_owned() - .unwrap(); - let (conn, state) = (Arc::clone(conn), Arc::clone(&f.state)); - tokio::spawn(async move { - let owner = close::admit(&sub, &conn).await.unwrap(); - artifact_sync::handle_sync(sub, owner, filter, conn, state, permit).await; - }) -} -async fn ended(task: tokio::task::JoinHandle<()>) { - tokio::time::timeout(Duration::from_secs(10), task) - .await - .unwrap() - .unwrap(); -} - -#[tokio::test] -#[ignore = "requires Postgres and Redis"] -async fn community_signal_lag_preserves_channel_sync() { - use buzz_pubsub::artifact_signal::{ArtifactChange, ArtifactSignal}; - use tokio::sync::{broadcast::error::TryRecvError, oneshot}; - - let f = community_fixture().await; - let owner = Keys::generate(); - member(&f, &owner, "owner").await; - let home = create_channel(&f.state, &f.tenant, &owner, &[]).await; - let (community, mut community_rx) = connect(&f, &owner); - let (channel, mut channel_rx) = connect(&f, &owner); - let community_task = start_sync(&f, &community, filter()); - let channel_task = start_sync(&f, &channel, sync_filter(&[home])); - assert!(initial_set(&mut community_rx).await.is_empty()); - assert!(initial_set(&mut channel_rx).await.is_empty()); - - // Subscribe now and start polling on a separate runtime only after Redis - // fills the receiver. This exercises actual lag without a test hook. - let (ready, ready_rx) = oneshot::channel(); - let (resume, resume_rx) = oneshot::channel(); - let cancel = f.state.community_revalidator_cancel.clone(); - let _shutdown = cancel.clone().drop_guard(); - let state = Arc::clone(&f.state); - let worker = tokio::task::spawn_blocking(move || { - let runtime = tokio::runtime::Builder::new_current_thread() - .build() - .unwrap(); - let signals = { - let _enter = runtime.enter(); - artifact_sync::spawn_signals(state) - }; - ready.send(()).unwrap(); - if resume_rx.blocking_recv().is_ok() { - runtime.block_on(signals).unwrap(); - } - }); - ready_rx.await.unwrap(); - - let mut probe = f.state.pubsub.subscribe_artifacts(); - let signal = ArtifactSignal { - d: Uuid::new_v4(), - artifact_type: "example.other".into(), - cause: ArtifactChange::Changed, - }; - tokio::time::timeout(Duration::from_secs(10), async { - // The local artifact broadcast holds 4096 messages. - for _ in 0..=4096 { - f.state - .pubsub - .publish_artifact(&f.tenant, &signal) - .await - .unwrap(); - } - while probe.len() <= 4096 { - tokio::task::yield_now().await; - } - }) - .await - .expect("local artifact signal receiver overflowed"); - assert!(matches!(probe.try_recv(), Err(TryRecvError::Lagged(_)))); - resume.send(()).unwrap(); - - assert_eq!( - frame(&mut community_rx).await, - json!(["CLOSED", "s", "resync: live delivery lagged"]) - ); - ended(community_task).await; - // Let the receiver finish handling lag before checking the channel sync. - cancel.cancel(); - worker.await.unwrap(); - - let created = super::revision(&f, &owner, home, Uuid::new_v4(), "create", None).await; - assert_eq!(live_event(&mut channel_rx).await, created.id.to_hex()); - close::handle_close("s".into(), channel, Arc::clone(&f.state)).await; - ended(channel_task).await; -} - -#[tokio::test] -#[ignore = "requires Postgres and Redis"] -async fn socket_revocation_or_local_policy_change_stops_initial_snapshot() { - for change in 2..6 { - let mut f = community_fixture().await; - Arc::make_mut(&mut Arc::get_mut(&mut f.state).unwrap().config) - .nip_fi - .mode = buzz_auth::NipFiMode::Shadow; - let keys = Keys::generate(); - let owner = Keys::generate(); - if change >= 3 { - Arc::get_mut(&mut f.state).unwrap().nip_fi_deny_map = - Some(Arc::new(buzz_auth::NipFiDenyMap::new( - 8, - vec![buzz_auth::IssuerCapacity { - issuer: "test-issuer".into(), - capacity: 8, - }], - ))); - } - member(&f, &keys, "member").await; - revision(&f, &keys, Uuid::new_v4(), None).await; - let (mut conn, mut rx) = connect(&f, &keys); - if change >= 3 { - Arc::get_mut(&mut conn).unwrap().nip_fi_assertion = Some( - buzz_auth::VerifiedAssertion::for_test( - Some(keys.public_key()), - vec![chrono::Utc::now() + chrono::Duration::hours(1)], - ) - .with_owner_for_test(owner.public_key()), - ); - } - let token = close::admit("s", &conn).await.unwrap(); - let pause = Arc::new(close::test_seam::Pause::default()); - let task = tokio::spawn( - artifact_sync::test_seam::QUEUE_CHECK_PAUSE.scope( - Arc::clone(&pause), - artifact_sync::handle_sync( - "s".into(), - token, - buzz_core::artifact_sync::parse_sync(&filter()), - Arc::clone(&conn), - Arc::clone(&f.state), - f.state - .handler_semaphore - .clone() - .try_acquire_owned() - .unwrap(), - ), - ), - ); - tokio::time::timeout(Duration::from_secs(10), pause.reached.notified()) - .await - .unwrap(); - match change { - 2 => { - sqlx::query("UPDATE communities SET requires_nip_fi=true,policy_generation=policy_generation+1 WHERE id=$1") - .bind(f.tenant.community().as_uuid()).execute(f.state.db.pool()).await.unwrap(); - f.state.invalidate_community_host(&f.tenant); - } - 3 | 4 => { - let key = if change == 3 { - keys.public_key() - } else { - owner.public_key() - }; - assert_eq!( - f.state - .nip_fi_deny_map - .as_ref() - .unwrap() - .merge_cross_pod_deny( - "test-issuer", - &key, - chrono::Utc::now() + chrono::Duration::hours(1), - chrono::Utc::now(), - ), - buzz_auth::CrossPodMergeResult::Merged - ); - } - _ => conn.nip_fi_gate.expire(|| {}).await, - } - pause.resume.notify_one(); - if change != 5 { - let response = frame(&mut rx).await; - assert_eq!(response[0], "CLOSED", "checkpoint {change}"); - assert!(response[2].as_str().unwrap().starts_with("resync:")); - } - ended(task).await; - no_frame(&mut rx).await; - if change == 2 { - let reopened = start_sync(&f, &conn, filter()); - let response = frame(&mut rx).await; - assert_eq!(response[0], "CLOSED"); - assert!(response[2].as_str().unwrap().starts_with("restricted:")); - ended(reopened).await; - no_frame(&mut rx).await; - } - } -} - -#[tokio::test] -#[ignore = "requires Postgres and Redis"] -async fn live_head_admission_denial_requires_resync() { - let f = community_fixture().await; - let signals = artifact_sync::spawn_signals(Arc::clone(&f.state)); - let writer = Keys::generate(); - let reader = Keys::generate(); - member(&f, &writer, "owner").await; - member(&f, &reader, "member").await; - let d = Uuid::new_v4(); - let first = revision(&f, &writer, d, None).await; - let (conn, mut rx) = connect(&f, &reader); - let task = start_sync(&f, &conn, filter()); - assert_eq!(initial_set(&mut rx).await, vec![first.id.to_hex()]); - - // Omit the invalidation so the next head read discovers the revocation. - remove(&f, &reader).await; - revision(&f, &writer, d, Some(&first)).await; - assert_eq!( - frame(&mut rx).await, - json!(["CLOSED", "s", "resync: community access changed"]) - ); - ended(task).await; - assert!(rx.try_recv().is_err()); - signals.abort(); -} - -#[tokio::test] -#[ignore = "requires Postgres and Redis"] -async fn community_sync_rejects_unauthenticated_readless_and_channel_bound_credentials() { - let f = community_fixture().await; - let keys = Keys::generate(); - member(&f, &keys, "member").await; - for case in 0..3 { - let (conn, mut rx) = connect(&f, &keys); - { - let mut state = conn.auth_state.lock().unwrap(); - if case == 0 { - *state = AuthState::Failed; - } else if let AuthState::Authenticated(ctx) = &mut *state { - if case == 1 { - ctx.scopes = vec![Scope::MessagesWrite]; - } else { - ctx.channel_ids = Some(vec![]); - } - } - } - let task = start_sync(&f, &conn, filter()); - assert_eq!(frame(&mut rx).await[0], "CLOSED"); - ended(task).await; - no_frame(&mut rx).await; - } - let first = revision(&f, &keys, Uuid::new_v4(), None).await; - let restricted = IngestAuth::Nip42 { - pubkey: keys.public_key(), - scopes: vec![Scope::MessagesWrite], - channel_ids: Some(vec![]), - conn_id: Uuid::new_v4(), - }; - assert!(ingest_event(&f.state, &f.tenant, first, restricted) - .await - .is_err()); -} - -#[tokio::test] -#[ignore = "requires Postgres and Redis"] -async fn two_nodes_resync_matching_community_artifacts_on_redaction() { - let f = community_fixture().await; - let local_fanout = artifact_sync::spawn_signals(Arc::clone(&f.state)); - let mut other = crate::api::bridge::postgres_tests::bridge_handler_test_state() - .await - .unwrap(); - let config = Arc::make_mut(&mut Arc::get_mut(&mut other).unwrap().config); - config.community_artifacts_enabled = true; - config.require_relay_membership = true; - tokio::spawn(Arc::clone(&other.pubsub).run_subscriber()); - other - .pubsub - .link_state() - .wait_for(|link| link.up) - .await - .unwrap(); - let remote = Fixture { - state: other, - tenant: f.tenant.clone(), - }; - let remote_fanout = artifact_sync::spawn_signals(Arc::clone(&remote.state)); - // Retain the ordinary topic independently: community payloads must never - // enter its unchanged ChannelEvent receiver on either relay. - let mut ordinary_a = f.state.pubsub.subscribe_local(); - let mut ordinary_b = remote.state.pubsub.subscribe_local(); - for node in [&f, &remote] { - node.state - .pubsub - .retain_topic(&node.tenant, buzz_pubsub::EventTopic::Global) - .await; - node.state - .pubsub - .confirm_topic(&node.tenant, buzz_pubsub::EventTopic::Global) - .await - .unwrap(); - } - let owner = Keys::generate(); - let reader = Keys::generate(); - member(&f, &owner, "owner").await; - member(&f, &reader, "member").await; - let first = revision(&f, &owner, Uuid::new_v4(), None).await; - let (a, mut arx) = connect(&f, &reader); - let (b, mut brx) = connect(&remote, &reader); - let at = start_sync(&f, &a, filter()); - let bt = start_sync(&remote, &b, filter()); - assert_eq!(initial_set(&mut arx).await, vec![first.id.to_hex()]); - assert_eq!(initial_set(&mut brx).await, vec![first.id.to_hex()]); - let current = revision( - &f, - &owner, - first.tags.identifier().unwrap().parse().unwrap(), - Some(&first), - ) - .await; - for rx in [&mut arx, &mut brx] { - let message = frame(rx).await; - assert_eq!(message[0], "EVENT"); - assert_eq!(message[2]["id"], current.id.to_hex()); - } - let unrelated = json!({"artifact":"current","scope":"community","#type":["example.other"]}); - let other_task = named_sync(&remote, &b, "other", unrelated); - assert!(initial_set(&mut brx).await.is_empty()); - // An equally named identity on a different Redis tenant cannot reach us. - let wrong = TenantContext::resolved( - buzz_core::CommunityId::from_uuid(Uuid::new_v4()), - "other.example", - ); - f.state - .pubsub - .publish_artifact( - &wrong, - &buzz_pubsub::artifact_signal::ArtifactSignal { - d: first.tags.identifier().unwrap().parse().unwrap(), - artifact_type: "example.settings".into(), - cause: buzz_pubsub::artifact_signal::ArtifactChange::Redacted, - }, - ) - .await - .unwrap(); - for rx in [&mut arx, &mut brx] { - no_frame(rx).await; - } - let historical = EventBuilder::new(Kind::Custom(9005), "") - .tags([ - Tag::parse(["community", &f.tenant.community().to_string()]).unwrap(), - Tag::event(first.id), - ]) - .sign_with_keys(&owner) - .unwrap(); - ingest_event(&f.state, &f.tenant, historical, auth(&owner)) - .await - .unwrap(); - for rx in [&mut arx, &mut brx] { - no_frame(rx).await; - } - assert!(ordinary_a.try_recv().is_err()); - assert!(ordinary_b.try_recv().is_err()); - let ordinary = EventBuilder::new(Kind::TextNote, "ordinary") - .sign_with_keys(&owner) - .unwrap(); - f.state - .pubsub - .publish_event(&f.tenant, buzz_pubsub::EventTopic::Global, &ordinary) - .await - .unwrap(); - for rx in [&mut ordinary_a, &mut ordinary_b] { - assert_eq!( - tokio::time::timeout(Duration::from_secs(5), rx.recv()) - .await - .unwrap() - .unwrap() - .event - .id, - ordinary.id - ); - assert!(rx.try_recv().is_err()); - } - let moderation = EventBuilder::new(Kind::Custom(9005), "") - .tags([ - Tag::parse(["community", &f.tenant.community().to_string()]).unwrap(), - Tag::event(current.id), - ]) - .sign_with_keys(&owner) - .unwrap(); - assert!( - ingest_event(&f.state, &f.tenant, moderation, auth(&owner)) - .await - .unwrap() - .accepted - ); - for rx in [&mut arx, &mut brx] { - let message = frame(rx).await; - assert_eq!(message[0], "CLOSED"); - assert!(message[2].as_str().unwrap().starts_with("resync:")); - } - ended(at).await; - ended(bt).await; - no_frame(&mut brx).await; - assert!(remote.state.artifact_syncs.contains(b.conn_id, "other")); - close::handle_close("other".into(), Arc::clone(&b), Arc::clone(&remote.state)).await; - assert_eq!(frame(&mut brx).await[0], "CLOSED"); - ended(other_task).await; - for node in [&f, &remote] { - assert_eq!( - node.state - .pubsub - .topic_refcount(&node.tenant, buzz_pubsub::EventTopic::CommunityArtifact) - .await, - 0 - ); - } - local_fanout.abort(); - remote_fanout.abort(); -} - -#[tokio::test] -#[ignore = "requires Postgres and Redis"] -async fn community_sync_retries_after_snapshot_capacity_is_exhausted() { - use futures_util::{SinkExt, StreamExt}; - use tokio_tungstenite::tungstenite::{client::IntoClientRequest, Message}; - use tokio_tungstenite::{MaybeTlsStream, WebSocketStream}; - - async fn read_frame( - client: &mut WebSocketStream>, - ) -> Value { - tokio::time::timeout(Duration::from_secs(10), async { - loop { - match client.next().await { - Some(Ok(Message::Text(text))) => return serde_json::from_str(&text).unwrap(), - Some(Ok(Message::Ping(_) | Message::Pong(_))) => continue, - other => panic!("expected a relay frame, got {other:?}"), - } - } - }) - .await - .expect("relay frame in time") - } - - let mut f = community_fixture().await; - let keys = Keys::generate(); - member(&f, &keys, "member").await; - let pool = sqlx::postgres::PgPoolOptions::new() - .max_connections(2) - .connect(&crate::test_support::database_url()) - .await - .unwrap(); - // A two-connection writer leaves one connection available for admission. - Arc::get_mut(&mut f.state).unwrap().db = buzz_db::Db::from_pool(pool); - - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = listener.local_addr().unwrap(); - let router = crate::router::build_router(Arc::clone(&f.state)); - let server = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); - let mut request = format!("ws://{address}/").into_client_request().unwrap(); - request - .headers_mut() - .insert("host", f.tenant.host().parse().unwrap()); - let (mut client, _) = tokio_tungstenite::connect_async(request).await.unwrap(); - let auth_challenge = read_frame(&mut client).await; - assert_eq!(auth_challenge[0], "AUTH"); - let relay = crate::api::bridge::nip42_expected_relay_url(&f.state.config.relay_url, &f.tenant); - let auth = EventBuilder::new(Kind::Authentication, "") - .tags([ - Tag::parse(["relay", &relay]).unwrap(), - Tag::parse(["challenge", auth_challenge[1].as_str().unwrap()]).unwrap(), - ]) - .sign_with_keys(&keys) - .unwrap(); - client - .send(Message::Text(json!(["AUTH", auth]).to_string().into())) - .await - .unwrap(); - let auth_response = read_frame(&mut client).await; - assert_eq!(auth_response[0], "OK", "{auth_response}"); - assert_eq!(auth_response[2], true, "{auth_response}"); - - let principal = buzz_db::community_artifact::CommunityArtifactPrincipal { - pubkey: keys.public_key().to_bytes().to_vec(), - verified_owner: None, - owner_admission: false, - require_membership: true, - reject_required_nip_fi: false, - }; - let held = f - .state - .db - .open_community_artifact_snapshot(f.tenant.community(), &principal) - .await - .unwrap(); - client - .send(Message::Text( - json!(["REQ", "busy", filter()]).to_string().into(), - )) - .await - .unwrap(); - assert_eq!( - read_frame(&mut client).await, - json!(["CLOSED", "busy", "error: sync read failed"]) - ); - - held.finish().await.unwrap(); - client - .send(Message::Text( - json!(["REQ", "retry", filter()]).to_string().into(), - )) - .await - .unwrap(); - assert_eq!(read_frame(&mut client).await, json!(["EOSE", "retry"])); - client.close(None).await.unwrap(); - server.abort(); -} - -#[tokio::test] -#[ignore = "requires Postgres and Redis"] -async fn unavailable_current_admission_has_no_snapshot_or_eose() { - let f = community_fixture().await; - let keys = Keys::generate(); - member(&f, &keys, "member").await; - revision(&f, &keys, Uuid::new_v4(), None).await; - let (conn, mut rx) = connect(&f, &keys); - // Simulate an unavailable authorization relation on this isolated DB. - sqlx::query("ALTER TABLE community_bans RENAME TO probe_unavailable_bans") - .execute(f.state.db.pool()) - .await - .unwrap(); - let task = start_sync(&f, &conn, filter()); - let response = frame(&mut rx).await; - assert_eq!(response[0], "CLOSED"); - ended(task).await; - assert!( - rx.try_recv().is_err(), - "no EVENT or EOSE after failed admission" - ); -} - -/// Direct AUTH may record an OA owner while OA admission is disabled. That -/// owner still restricts reads/writes, but only enabled OA or verified FI may -/// supply a missing roster entry. Exercise actual signed AUTH and EVENT. -#[tokio::test] -#[ignore = "requires Postgres and Redis"] -async fn owner_restrictions_and_roster_fallback_remain_separate_after_direct_auth() { - for mode in 0..3 { - let mut f = community_fixture().await; - Arc::make_mut(&mut Arc::get_mut(&mut f.state).unwrap().config).allow_nip_oa_auth = - mode == 1; - let owner = Keys::generate(); - let agent = Keys::generate(); - member(&f, &owner, "owner").await; - member(&f, &agent, "member").await; - let (mut conn, mut rx) = connect(&f, &agent); - if mode == 2 { - let inner = Arc::get_mut(&mut conn).unwrap(); - inner.nip_fi_assertion = Some( - buzz_auth::VerifiedAssertion::for_test( - Some(agent.public_key()), - vec![chrono::Utc::now() + chrono::Duration::hours(1)], - ) - .with_owner_for_test(owner.public_key()), - ); - } - *conn.auth_state.lock().unwrap() = AuthState::Pending { - challenge: "owner-context".into(), - started_at: std::time::Instant::now(), - }; - let proof: Vec = serde_json::from_str( - &buzz_sdk::nip_oa::compute_auth_tag(&owner, &agent.public_key(), "").unwrap(), - ) - .unwrap(); - let auth = EventBuilder::new(Kind::Authentication, "") - .tags([ - Tag::parse([ - "relay", - &crate::api::bridge::nip42_expected_relay_url( - &f.state.config.relay_url, - &f.tenant, - ), - ]) - .unwrap(), - Tag::parse(["challenge", "owner-context"]).unwrap(), - Tag::parse(proof).unwrap(), - ]) - .sign_with_keys(&agent) - .unwrap(); - crate::handlers::auth::handle_auth(auth.clone(), Arc::clone(&conn), Arc::clone(&f.state)) - .await; - let reply = frame(&mut rx).await; - assert_eq!(reply[2], true, "mode {mode}: AUTH: {reply}"); - let AuthState::Authenticated(ctx) = conn.auth_state_snapshot() else { - panic!("AUTH failed") - }; - assert_eq!(ctx.agent_owner_pubkey, Some(owner.public_key())); - let first = signed_revision(&f, &agent, Uuid::new_v4(), None); - event_handler::handle_event(first.clone(), Arc::clone(&conn), Arc::clone(&f.state)).await; - assert_eq!(frame(&mut rx).await[2], true); - let sync = start_sync(&f, &conn, filter()); - assert_eq!(initial_set(&mut rx).await, vec![first.id.to_hex()]); - // The same key and OA proof on a second socket have no FI credential. - // Its live admission must be checked independently of the FI-backed socket. - let oa_only = if mode == 2 { - let (other, mut other_rx) = connect(&f, &agent); - *other.auth_state.lock().unwrap() = AuthState::Pending { - challenge: "owner-context".into(), - started_at: std::time::Instant::now(), - }; - crate::handlers::auth::handle_auth(auth, Arc::clone(&other), Arc::clone(&f.state)) - .await; - assert_eq!(frame(&mut other_rx).await[2], true); - let task = start_sync(&f, &other, filter()); - assert_eq!(initial_set(&mut other_rx).await, vec![first.id.to_hex()]); - Some((other, other_rx, task)) - } else { - None - }; - let signal = buzz_pubsub::artifact_signal::ArtifactSignal { - d: first.tags.identifier().unwrap().parse().unwrap(), - artifact_type: "example.settings".into(), - cause: buzz_pubsub::artifact_signal::ArtifactChange::Changed, - }; - remove(&f, &agent).await; // Deliberately omit disconnects. - f.state - .artifact_syncs - .signal_community(f.tenant.community(), &signal); - if let Some((other, mut other_rx, task)) = oa_only { - assert_eq!(frame(&mut other_rx).await[0], "CLOSED"); - ended(task).await; - event_handler::handle_event( - signed_revision(&f, &agent, Uuid::new_v4(), None), - other, - Arc::clone(&f.state), - ) - .await; - assert_eq!(frame(&mut other_rx).await[2], false); - } - if mode == 0 { - assert_eq!(frame(&mut rx).await[0], "CLOSED"); - ended(sync).await; - } else { - let live = frame(&mut rx).await; - assert_eq!(live[0], "EVENT"); - assert_eq!(live[2]["id"], first.id.to_hex()); - close::handle_close("s".into(), Arc::clone(&conn), Arc::clone(&f.state)).await; - assert_eq!(frame(&mut rx).await[0], "CLOSED"); - ended(sync).await; - } - let next = signed_revision(&f, &agent, Uuid::new_v4(), None); - event_handler::handle_event(next, Arc::clone(&conn), Arc::clone(&f.state)).await; - assert_eq!( - frame(&mut rx).await[2], - mode != 0, - "mode {mode}: fallback write" - ); - if mode == 0 { - member(&f, &agent, "member").await; - } - sqlx::query("INSERT INTO community_bans(community_id,pubkey,actor_pubkey,muted_until) VALUES($1,$2,$2,clock_timestamp()+interval '5 minutes')") - .bind(f.tenant.community().as_uuid()).bind(owner.public_key().as_bytes().as_slice()) - .execute(f.state.db.pool()).await.unwrap(); - event_handler::handle_event(first.clone(), Arc::clone(&conn), Arc::clone(&f.state)).await; - assert_eq!( - frame(&mut rx).await[2], - true, - "timeout permits exact replay" - ); - let next = signed_revision(&f, &agent, Uuid::new_v4(), None); - event_handler::handle_event(next, Arc::clone(&conn), Arc::clone(&f.state)).await; - assert_eq!( - frame(&mut rx).await[2], - false, - "owner timeout blocks new content" - ); - let sync = start_sync(&f, &conn, filter()); - assert!( - !initial_set(&mut rx).await.is_empty(), - "timeout permits reads" - ); - sqlx::query("UPDATE community_bans SET banned=true WHERE community_id=$1 AND pubkey=$2") - .bind(f.tenant.community().as_uuid()) - .bind(owner.public_key().as_bytes().as_slice()) - .execute(f.state.db.pool()) - .await - .unwrap(); - f.state - .artifact_syncs - .signal_community(f.tenant.community(), &signal); - assert_eq!(frame(&mut rx).await[0], "CLOSED"); - ended(sync).await; - event_handler::handle_event(first, Arc::clone(&conn), Arc::clone(&f.state)).await; - assert_eq!(frame(&mut rx).await[2], false, "owner ban blocks replay"); - no_frame(&mut rx).await; - } -} diff --git a/crates/buzz-relay/src/handlers/close.rs b/crates/buzz-relay/src/handlers/close.rs index 42b38b1d614..395aacfe4da 100644 --- a/crates/buzz-relay/src/handlers/close.rs +++ b/crates/buzz-relay/src/handlers/close.rs @@ -259,12 +259,6 @@ pub(crate) async fn release_scope_topics( tenant: &TenantContext, scope: &SubscriptionScope, ) { - if scope.is_community_artifact() { - state - .pubsub - .release_topic(tenant, EventTopic::CommunityArtifact) - .await; - } if scope.is_global() { state.pubsub.release_topic(tenant, EventTopic::Global).await; } diff --git a/crates/buzz-relay/src/handlers/community_artifact.rs b/crates/buzz-relay/src/handlers/community_artifact.rs deleted file mode 100644 index 674389a5ac1..00000000000 --- a/crates/buzz-relay/src/handlers/community_artifact.rs +++ /dev/null @@ -1,325 +0,0 @@ -//! Explicit community artifacts: transport authorization precedes receipts; -//! edit policy is checked only for a new write, in its accepting transaction. -use super::ingest::{ - IngestAuth, IngestError, IngestResult, MAX_EVENT_CONTENT_BYTES, MAX_TIMESTAMP_DRIFT_SECS, -}; -use crate::state::AppState; -use buzz_auth::Scope; -use buzz_core::{ - artifact::{self, ArtifactScope}, - TenantContext, -}; -use buzz_db::community_artifact::{CommunityArtifactPrincipal, PolicyOutcome}; -use nostr::Event; -use std::sync::Arc; - -/// AuthContext records owners for revocation even when OA admission is off. -/// Only a verified FI agent credential or current OA policy permits fallback. -pub(crate) fn owner_admission( - state: &AppState, - conn: &crate::connection::ConnectionState, - owner: Option, -) -> bool { - state.config.allow_nip_oa_auth - || conn - .nip_fi_assertion - .as_ref() - .and_then(|assertion| assertion.owner()) - .is_some_and(|verified| Some(verified) == owner) -} - -pub(crate) fn principal(state: &AppState, auth: &IngestAuth) -> CommunityArtifactPrincipal { - CommunityArtifactPrincipal { - pubkey: auth.pubkey().to_bytes().to_vec(), - verified_owner: auth.verified_owner().map(|p| p.to_bytes().to_vec()), - owner_admission: auth.owner_admission(), - require_membership: state.config.require_relay_membership, - reject_required_nip_fi: false, - } -} -pub(crate) fn storage_error(error: buzz_db::DbError) -> IngestError { - match error { - buzz_db::DbError::AccessDenied(_) => { - IngestError::AuthFailed("restricted: community artifact access denied".into()) - } - buzz_db::DbError::NotFound(_) => { - IngestError::Rejected("invalid: community artifact unavailable".into()) - } - buzz_db::DbError::InvalidData(message) => { - IngestError::Rejected(format!("invalid: {message}")) - } - _ => IngestError::Internal("error: community artifact operation unavailable".into()), - } -} -pub(crate) async fn enabled(state: &AppState) -> Result { - if !state.config.community_artifacts_enabled { - return Ok(false); - } - state - .community_artifact_schema - .get_or_try_init(|| state.db.community_artifact_schema_ready()) - .await - .copied() -} -fn invalid(reason: &str) -> IngestError { - IngestError::Rejected(format!("invalid: {reason}")) -} -fn credential(auth: &IngestAuth, event: &Event, scope: Scope) -> Result<(), IngestError> { - if !auth.signed_transport() - || auth.pubkey() != &event.pubkey - || auth.channel_ids().is_some() - || !auth.scopes().contains(&scope) - { - return Err(IngestError::AuthFailed( - "restricted: unrestricted authenticated community credential required".into(), - )); - } - Ok(()) -} -/// Route only explicitly scoped operations. Every other kind keeps its existing -/// pipeline. The shared ingest seam has already verified the event signature. -pub(crate) async fn ingest( - state: &Arc, - tenant: &TenantContext, - event: &Event, - auth: &IngestAuth, -) -> Option> { - let kind = event.kind.as_u16(); - let community_tag = event - .tags - .iter() - .any(|t| t.as_slice().first().is_some_and(|n| n == "community")); - if kind == 9005 && !community_tag { - let h: Vec<_> = event - .tags - .iter() - .filter(|t| t.as_slice().first().is_some_and(|n| n == "h")) - .collect(); - if h.len() != 1 - || h[0] - .as_slice() - .get(1) - .is_none_or(|id| uuid::Uuid::parse_str(id).is_err()) - { - return Some(Err(invalid( - "9005 requires exactly one channel or community scope", - ))); - } - return None; - } - if kind != 9034 && !(community_tag && matches!(kind, 45010 | 9005)) { - return None; - } - Some(execute(state, tenant, event, auth).await) -} -async fn execute( - state: &Arc, - tenant: &TenantContext, - event: &Event, - auth: &IngestAuth, -) -> Result { - let community = tenant.community(); - let kind = event.kind.as_u16(); - // Parsing and signed tenant binding always precede accepted-command state. - let env = if kind == 45010 { - let env = artifact::validate(event).map_err(invalid)?; - if env.scope != ArtifactScope::Community || env.community != Some(*community.as_uuid()) { - return Err(invalid("community scope does not match request tenant")); - } - Some(env) - } else { - None - }; - let command = if kind == 9034 { - let command = artifact::parse_policy_command(event).map_err(invalid)?; - if command.community != *community.as_uuid() { - return Err(invalid("community scope does not match request tenant")); - } - Some(command) - } else { - None - }; - let target = if kind == 9005 { - Some(moderation_target(event, tenant)?) - } else { - None - }; - let scope = match kind { - 9034 => Scope::AdminUsers, - 9005 => Scope::MessagesWrite, - _ => Scope::MessagesWrite, - }; - credential(auth, event, scope)?; - if !enabled(state).await.map_err(storage_error)? { - return Err(invalid( - "community artifacts are not enabled on a compatible schema", - )); - } - let principal = principal(state, auth); - if let Some(env) = env { - // An accepted replay is acknowledgement only: no content, publish, edit - // policy, timeout or freshness check. Admission still includes bans. - if state - .db - .community_artifact_accepted(community, &principal, event) - .await - .map_err(storage_error)? - { - return Ok(ack(event)); - } - let now = chrono::Utc::now().timestamp(); - if event.created_at.as_secs().abs_diff(now as u64) > MAX_TIMESTAMP_DRIFT_SECS as u64 { - return Err(invalid("event timestamp too far from server time")); - } - if event.content.len() > MAX_EVENT_CONTENT_BYTES { - return Err(invalid("event content too large")); - } - super::media_access::validate_media_references(tenant, state, event).await?; - let base = - crate::api::media::media_base_url_for_tenant(&state.config.relay_url, tenant.host()); - super::ingest::validate_event_imeta(tenant, state, event, &base).await?; - super::artifact::verify_revision_auth(event)?; - let outcome = state - .db - .accept_community_artifact(community, &principal, event, &env) - .await - .map_err(storage_error)?; - if !super::artifact::accepted_events(outcome)?.is_empty() { - signal( - state, - tenant, - buzz_pubsub::artifact_signal::ArtifactSignal { - d: env.id, - artifact_type: env.artifact_type, - cause: buzz_pubsub::artifact_signal::ArtifactChange::Changed, - }, - ) - .await; - } - } else if let Some(command) = command { - super::ingest::enforce_write_restriction( - state, - tenant, - buzz_core::kind::RELAY_ADMIN_SET_ARTIFACT_TYPE_POLICY, - auth.pubkey(), - ) - .await?; - let mut tx = - state.db.pool().begin().await.map_err(|_| { - IngestError::Internal("error: policy transaction unavailable".into()) - })?; - match buzz_db::community_artifact::set_policy_in_transaction( - &mut tx, community, &principal, event, &command, - ) - .await - .map_err(storage_error)? - { - PolicyOutcome::Conflict(reason) => { - return Err(IngestError::CanvasConflict(format!("conflict: {reason}"))) - } - PolicyOutcome::Duplicate => {} - PolicyOutcome::Applied => { - buzz_audit::AuditService::log_in_transaction(&mut tx,buzz_audit::NewAuditEntry { - community_id:community,action:buzz_audit::AuditAction::EventCreated,actor_pubkey:Some(principal.pubkey),object_id:Some(event.id.to_hex()), - detail:serde_json::json!({"command":"set_artifact_type_policy","event_kind":9034,"type":command.artifact_type,"policy":command.policy,"prev":command.prev}), - }).await.map_err(|_|IngestError::Internal("error: policy audit unavailable".into()))?; - } - } - tx.commit() - .await - .map_err(|_| IngestError::Internal("error: policy commit unavailable".into()))?; - } else if let Some(target) = target { - if event.content.len() > MAX_EVENT_CONTENT_BYTES { - return Err(invalid("event content too large")); - } - let now = chrono::Utc::now().timestamp(); - if event.created_at.as_secs().abs_diff(now as u64) > MAX_TIMESTAMP_DRIFT_SECS as u64 { - return Err(invalid("event timestamp too far from server time")); - } - if let Some((d, artifact_type)) = state - .db - .redact_community_artifact(community, &principal, &target) - .await - .map_err(storage_error)? - { - signal( - state, - tenant, - buzz_pubsub::artifact_signal::ArtifactSignal { - d, - artifact_type, - cause: buzz_pubsub::artifact_signal::ArtifactChange::Redacted, - }, - ) - .await; - } - } - Ok(ack(event)) -} -fn ack(event: &Event) -> IngestResult { - IngestResult { - event_id: event.id.to_hex(), - accepted: true, - message: String::new(), - } -} -/// Community moderation is discriminated by the signed scope, never by an -/// absent/nullable channel decoded from the target. -fn moderation_target(event: &Event, tenant: &TenantContext) -> Result, IngestError> { - let mut community = None; - let mut target = None; - for tag in event.tags.iter() { - let parts = tag.as_slice(); - match parts.first().map(String::as_str) { - Some("h") => return Err(invalid("mixed moderation scope")), - Some("community") => { - if parts.len() != 2 || community.is_some() { - return Err(invalid("exactly one community scope required")); - } - community = Some(artifact::canonical_uuid(&parts[1]).map_err(invalid)?); - } - Some("e") => { - if parts.len() != 2 || target.is_some() { - return Err(invalid("exactly one target revision required")); - } - target = Some(artifact::event_id(&parts[1]).map_err(invalid)?); - } - _ => {} - } - } - if community != Some(*tenant.community().as_uuid()) { - return Err(invalid("community scope does not match request tenant")); - } - target.ok_or_else(|| invalid("one target revision required")) -} -/// Compact metadata reaches every node, including this one, through the same -/// confirmed Redis interest. Retry until success or shutdown; no content is fanned out. -async fn signal( - state: &Arc, - tenant: &TenantContext, - signal: buzz_pubsub::artifact_signal::ArtifactSignal, -) { - if state.pubsub.publish_artifact(tenant, &signal).await.is_ok() { - return; - } - let state = Arc::clone(state); - let tenant = tenant.clone(); - tokio::spawn(async move { - let mut delay = std::time::Duration::from_millis(100); - loop { - tokio::select! { - () = state.community_revalidator_cancel.cancelled() => return, - () = tokio::time::sleep(delay) => {} - } - if state - .pubsub - .publish_artifact(&tenant, &signal) - .await - .is_ok() - { - return; - } - delay = (delay * 2).min(std::time::Duration::from_secs(5)); - } - }); -} diff --git a/crates/buzz-relay/src/handlers/event.rs b/crates/buzz-relay/src/handlers/event.rs index 75f03a48c66..ec80f34339e 100644 --- a/crates/buzz-relay/src/handlers/event.rs +++ b/crates/buzz-relay/src/handlers/event.rs @@ -152,21 +152,6 @@ async fn check_fanout_access( matches: Vec<(crate::subscription::ConnId, crate::subscription::SubId)>, threaded: Option<&crate::state::ThreadedChannelVisibility>, ) -> FanoutAccess { - // Ordinary delivery has no community artifact audience. This fence is - // unconditional, including callers that use the access helper directly. - if stored_event.event.kind.as_u16() == 45010 - && (stored_event.channel_id.is_none() - || stored_event.event.tags.iter().any(|tag| { - tag.as_slice() - .first() - .is_some_and(|name| name == "community") - })) - { - return FanoutAccess { - allowed: Vec::new(), - unverified: Vec::new(), - }; - } let verified = |allowed| FanoutAccess { allowed, unverified: Vec::new(), @@ -330,17 +315,6 @@ pub(crate) async fn route_fanout_matches( matches: Vec<(crate::subscription::ConnId, crate::subscription::SubId)>, threaded: Option<&crate::state::ThreadedChannelVisibility>, ) -> Vec<(crate::subscription::ConnId, crate::subscription::SubId)> { - let kind = stored.event.kind.as_u16(); - let community_tag = stored - .event - .tags - .iter() - .any(|t| t.as_slice().first().is_some_and(|n| n == "community")); - if (kind == 45010 && (stored.channel_id.is_none() || community_tag)) - || (kind == 9005 && community_tag) - { - return vec![]; - } state.artifact_syncs.signal_access_change(stored, &matches); let access = check_fanout_access(state, community_id, stored, matches, threaded).await; // A sync that the gate could not check loses this change, so its copy is @@ -443,7 +417,7 @@ pub(crate) fn take_local_echo(state: &AppState, channel_event: &buzz_pubsub::Cha pub(crate) fn pubsub_stored_event(channel_event: buzz_pubsub::ChannelEvent) -> StoredEvent { let channel_id = match channel_event.topic { buzz_pubsub::EventTopic::Channel(id) => Some(id), - buzz_pubsub::EventTopic::Global | buzz_pubsub::EventTopic::CommunityArtifact => None, + buzz_pubsub::EventTopic::Global => None, }; StoredEvent::new(channel_event.event, channel_id) } @@ -742,7 +716,7 @@ pub async fn handle_event(event: Event, conn: Arc, state: Arc ( conn.conn_id, @@ -750,7 +724,6 @@ pub async fn handle_event(event: Event, conn: Arc, state: Arc { reject("auth"); @@ -962,11 +935,7 @@ pub async fn handle_event(event: Event, conn: Arc, state: Arc, - /// Owner proven by the authenticated transport. - owner: nostr::PublicKey, - /// Current transport policy permits owner roster fallback. - owner_admission: bool, - }, /// WebSocket NIP-42 authenticated connection. Nip42 { /// The authenticated Nostr public key. @@ -338,56 +325,10 @@ pub enum IngestAuth { } impl IngestAuth { - /// Attach only an owner verified by the current transport admission. - pub fn with_verified_owner(self, owner: Option) -> Self { - self.with_owner_admission(owner, true) - } - /// Keep restriction identity separately from permission to use its roster. - pub fn with_owner_admission( - self, - owner: Option, - owner_admission: bool, - ) -> Self { - match owner { - Some(owner) => Self::Delegated { - auth: Box::new(self), - owner, - owner_admission, - }, - None => self, - } - } - /// Proven delegated owner, independently of any artifact tag or payload. - pub fn verified_owner(&self) -> Option { - match self { - Self::Delegated { owner, .. } => Some(*owner), - _ => None, - } - } - /// Whether the verified owner may supply current relay membership. - pub fn owner_admission(&self) -> bool { - matches!( - self, - Self::Delegated { - owner_admission: true, - .. - } - ) - } - /// Community operations require the relay's signed authenticated transport. - pub fn signed_transport(&self) -> bool { - match self { - Self::Delegated { auth, .. } => auth.signed_transport(), - Self::Nip42 { .. } => true, - Self::Http { auth_method, .. } => matches!(auth_method, HttpAuthMethod::Nip98), - } - } - /// The authenticated public key. pub fn pubkey(&self) -> &nostr::PublicKey { match self { Self::Nip42 { pubkey, .. } | Self::Http { pubkey, .. } => pubkey, - Self::Delegated { auth, .. } => auth.pubkey(), } } @@ -400,7 +341,6 @@ impl IngestAuth { pub fn scopes(&self) -> &[Scope] { match self { Self::Nip42 { scopes, .. } | Self::Http { scopes, .. } => scopes, - Self::Delegated { auth, .. } => auth.scopes(), } } @@ -409,7 +349,6 @@ impl IngestAuth { match self { Self::Nip42 { conn_id, .. } => Some(*conn_id), Self::Http { .. } => None, - Self::Delegated { auth, .. } => auth.conn_id(), } } @@ -422,17 +361,13 @@ impl IngestAuth { channel_ids: Some(ids), .. } => Some(ids), - Self::Delegated { auth, .. } => auth.channel_ids(), _ => None, } } /// Whether this auth context is an HTTP request (not WebSocket). pub fn is_http(&self) -> bool { - match self { - Self::Delegated { auth, .. } => auth.is_http(), - _ => matches!(self, Self::Http { .. }), - } + matches!(self, Self::Http { .. }) } } @@ -718,7 +653,7 @@ fn required_scope_for_kind(kind: u32, event: &Event) -> Result + || k == RELAY_ADMIN_SET_WORKSPACE_PROFILE => { Ok(Scope::AdminUsers) } @@ -931,7 +866,6 @@ pub(crate) fn is_global_only_kind(kind: u32) -> bool { | RELAY_ADMIN_REMOVE_MEMBER | RELAY_ADMIN_CHANGE_ROLE | RELAY_ADMIN_SET_WORKSPACE_PROFILE - | RELAY_ADMIN_SET_ARTIFACT_TYPE_POLICY | KIND_NIP43_LEAVE_REQUEST // NIP-IA: identity archive/unarchive requests drive relay-global // archive state (8002/8003/13535) and are audited as global request @@ -2617,7 +2551,7 @@ struct ChannelCreateRequest { members: Vec>, } -pub(super) async fn validate_event_imeta( +async fn validate_event_imeta( tenant: &TenantContext, state: &AppState, event: &Event, @@ -2709,17 +2643,6 @@ async fn ingest_event_inner( } let event = std::sync::Arc::try_unwrap(event).unwrap_or_else(|arc| (*arc).clone()); - if let Some(result) = super::community_artifact::ingest(state, tenant, &event, &auth).await { - let result = result?; - emit_product_feedback_success(tracer, tenant, &event, &auth); - return Ok(result); - } - if kind_u32 == buzz_core::kind::KIND_ARTIFACT { - // Reject mixed/repeated scopes before even a channel receipt lookup. - buzz_core::artifact::validate(&event) - .map_err(|e| IngestError::Rejected(format!("invalid: {e}")))?; - } - if kind_u32 == buzz_core::kind::KIND_ARTIFACT && event.pubkey == *auth.pubkey() && state @@ -2747,6 +2670,7 @@ async fn ingest_event_inner( }); } + const MAX_TIMESTAMP_DRIFT_SECS: i64 = 900; // ±15 minutes let now = chrono::Utc::now().timestamp(); let event_ts = event.created_at.as_secs() as i64; if (event_ts - now).abs() > MAX_TIMESTAMP_DRIFT_SECS { @@ -2763,6 +2687,7 @@ async fn ingest_event_inner( } } + const MAX_EVENT_CONTENT_BYTES: usize = 256 * 1024; // 256 KB if event.content.len() > MAX_EVENT_CONTENT_BYTES { return Err(IngestError::Rejected(format!( "invalid: content exceeds maximum size of {} bytes (got {})", diff --git a/crates/buzz-relay/src/handlers/mod.rs b/crates/buzz-relay/src/handlers/mod.rs index c6849df635d..ad1284feda7 100644 --- a/crates/buzz-relay/src/handlers/mod.rs +++ b/crates/buzz-relay/src/handlers/mod.rs @@ -14,8 +14,6 @@ pub mod close; pub mod coalesced_refresh; /// Command executor — transactional processing for command kinds. pub mod command_executor; -/// NIP-AR explicit community operations and admission. -pub(crate) mod community_artifact; /// Relay-operator community provisioning HTTP support. pub mod community_provisioning; /// NIP-45 COUNT handler. diff --git a/crates/buzz-relay/src/handlers/side_effects.rs b/crates/buzz-relay/src/handlers/side_effects.rs index df41c9ac9ce..afa25fd20f2 100644 --- a/crates/buzz-relay/src/handlers/side_effects.rs +++ b/crates/buzz-relay/src/handlers/side_effects.rs @@ -521,12 +521,7 @@ pub async fn validate_standard_deletion_event( return Err(anyhow::anyhow!("invalid a-tag format")); } if let Ok(target_kind) = parts[0].parse() { - if matches!( - target_kind, - KIND_VERIFIED_PROFILE - | buzz_core::kind::KIND_ARTIFACT - | buzz_core::kind::KIND_ARTIFACT_REMOVAL - ) { + if target_kind == KIND_VERIFIED_PROFILE { anyhow::bail!(DELETION_TARGET_DENIED); } check_deletion_privacy_k_tag(event, target_kind)?; diff --git a/crates/buzz-relay/src/main.rs b/crates/buzz-relay/src/main.rs index 5fe7f9aad9c..3d233bc25c9 100644 --- a/crates/buzz-relay/src/main.rs +++ b/crates/buzz-relay/src/main.rs @@ -1284,8 +1284,6 @@ async fn run_relay_main(boot: BootTracker) -> anyhow::Result<()> { }); } - buzz_relay::handlers::artifact_sync::spawn_signals(Arc::clone(&state)); - // NIP-AR Sync: a possible loss on the Redis link resyncs every sync. tokio::spawn(buzz_relay::handlers::artifact_sync::watch_link(Arc::clone( &state, diff --git a/crates/buzz-relay/src/nip11.rs b/crates/buzz-relay/src/nip11.rs index c4f61f018a6..7feb2e4c5d9 100644 --- a/crates/buzz-relay/src/nip11.rs +++ b/crates/buzz-relay/src/nip11.rs @@ -480,14 +480,6 @@ pub(crate) async fn nip11_document( info.requires_nip_fi = policy.required; info.workflow_agent_mentions = state.config.workflow_agent_mentions; info.artifacts["incremental"] = crate::api::artifact_sync::capability(); - if let Some(tenant) = tenant.as_ref() { - if crate::handlers::community_artifact::enabled(state) - .await - .unwrap_or(false) - { - info.artifacts["community_scope"] = serde_json::json!({"version":1,"community_id":tenant.community().as_uuid().to_string(),"max_policies":buzz_core::artifact::MAX_COMMUNITY_POLICIES}); - } - } if let Some(tenant) = tenant.as_ref() { if let Some(profile) = crate::verified_profiles::discovery(state, tenant).await { if let Some(fi) = info.federated_identity.as_mut() { diff --git a/crates/buzz-relay/src/protocol.rs b/crates/buzz-relay/src/protocol.rs index 92f01e8faf2..58c1a188a91 100644 --- a/crates/buzz-relay/src/protocol.rs +++ b/crates/buzz-relay/src/protocol.rs @@ -315,8 +315,6 @@ mod tests { r##"["REQ","ar",{"artifact":"history","#d":["artifact"]}]"##.to_owned(), r##"["REQ","ar",{"kinds":[45010],"#project":["project"]}]"##.to_owned(), r##"["COUNT","ar",{"artifact":"current"}]"##.to_owned(), - r##"["REQ","ar",{"scope":"community"}]"##.to_owned(), - r##"["COUNT","ar",{"scope":"community"}]"##.to_owned(), // No `kinds` may match artifacts, so the predicate cannot be dropped. format!(r##"["REQ","ar",{{"ids":["{id}"],"#project":["P"]}}]"##), format!(r##"["COUNT","ar",{{"ids":["{id}"],"#project":["P"]}}]"##), diff --git a/crates/buzz-relay/src/state.rs b/crates/buzz-relay/src/state.rs index d97966d6ea0..361cf6d3715 100644 --- a/crates/buzz-relay/src/state.rs +++ b/crates/buzz-relay/src/state.rs @@ -1438,8 +1438,6 @@ pub struct AppState { pub(crate) search_slots: Arc, /// Registry of active client subscriptions. pub sub_registry: Arc, - /// Startup-cached verification of the optional operator schema contract. - pub(crate) community_artifact_schema: tokio::sync::OnceCell, /// Live NIP-AR syncs this node serves. pub artifact_syncs: Arc, /// Registry of active WebSocket connections. @@ -1813,7 +1811,6 @@ impl AppState { search_slots: Arc::default(), sub_registry: Arc::new(SubscriptionRegistry::new()), artifact_syncs: Arc::default(), - community_artifact_schema: tokio::sync::OnceCell::new(), conn_manager: Arc::new(ConnectionManager::new()), community_connections: Arc::new(CommunityConnectionRegistry::new()), community_revalidator_cancel: CancellationToken::new(), @@ -2252,7 +2249,6 @@ impl AppState { ) { match invalidation { CacheInvalidation::CommunityHost { host } => { - self.artifact_syncs.resync_community(community_id); self.tenant_host_cache.invalidate(&host); self.community_active.invalidate(&community_id); } @@ -2277,7 +2273,6 @@ impl AppState { /// Drop the host's policy/routing snapshot locally and best-effort on peers. /// Lease expiry, not notification delivery, protects acceptance consistency. pub fn invalidate_community_host(&self, tenant: &TenantContext) { - self.artifact_syncs.resync_community(tenant.community()); self.tenant_host_cache.invalidate(tenant.host()); self.community_active.invalidate(&tenant.community()); self.spawn_cache_invalidation( diff --git a/crates/buzz-relay/src/subscription.rs b/crates/buzz-relay/src/subscription.rs index 44d54bde19a..e72608ec3fc 100644 --- a/crates/buzz-relay/src/subscription.rs +++ b/crates/buzz-relay/src/subscription.rs @@ -28,7 +28,6 @@ pub type SubId = String; #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct SubscriptionScope { global: bool, - community_artifact: bool, channels: Vec, } @@ -37,24 +36,10 @@ impl SubscriptionScope { pub fn global() -> Self { Self { global: true, - community_artifact: false, channels: Vec::new(), } } - /// Dedicated artifact signals only, without any ordinary-event match. - pub(crate) fn community_artifacts() -> Self { - Self { - community_artifact: true, - ..Self::default() - } - } - - /// Whether this scope retains the dedicated artifact topic. - pub(crate) fn is_community_artifact(&self) -> bool { - self.community_artifact - } - /// Events from any of these authorized channels. Duplicates are dropped. pub fn channels(channel_ids: impl IntoIterator) -> Self { let mut scope = Self::default(); @@ -92,7 +77,7 @@ impl SubscriptionScope { } fn is_empty(&self) -> bool { - !self.global && !self.community_artifact && self.channels.is_empty() + !self.global && self.channels.is_empty() } /// The union of `scopes`: every topic any of them retains, once. @@ -100,7 +85,6 @@ impl SubscriptionScope { let mut union = Self::default(); for scope in scopes { union.global |= scope.global; - union.community_artifact |= scope.community_artifact; for &channel_id in &scope.channels { union.add_channel(channel_id); } diff --git a/crates/buzz-search/src/query.rs b/crates/buzz-search/src/query.rs index 0fa1b00ff81..170d600ecc3 100644 --- a/crates/buzz-search/src/query.rs +++ b/crates/buzz-search/src/query.rs @@ -329,13 +329,8 @@ pub async fn search(pool: &PgPool, query: &SearchQuery) -> Result 45010 OR (events.channel_id IS NOT NULL AND NOT ", - buzz_db::community_artifact_tag_sql!("events.tags"), - "))", - )); // Search is a current-state surface; old artifact snapshots cannot match. - qb.push(" AND (events.kind <> 45010 OR EXISTS (SELECT 1 FROM artifact_heads ah WHERE ah.community_id=events.community_id AND ah.event_id=events.id AND ah.scope='channel' AND NOT ah.deleted))"); + qb.push(" AND (events.kind <> 45010 OR EXISTS (SELECT 1 FROM artifact_heads ah WHERE ah.community_id=events.community_id AND ah.event_id=events.id AND NOT ah.deleted))"); // Channel scope — see `ChannelScope` doc for the four-case mapping. The // emitted SQL fragments are identical to the legacy 2x2 tuple for the diff --git a/crates/buzz-search/tests/postgres_fts_integration.rs b/crates/buzz-search/tests/postgres_fts_integration.rs index 0e762f05559..1cc084b2376 100644 --- a/crates/buzz-search/tests/postgres_fts_integration.rs +++ b/crates/buzz-search/tests/postgres_fts_integration.rs @@ -1852,7 +1852,7 @@ async fn artifact_search_uses_only_live_current_head() { let pk = rand_bytes32(); let old = rand_bytes32(); let head = rand_bytes32(); - let (artifact, home) = (Uuid::new_v4(), Uuid::new_v4()); + let artifact = Uuid::new_v4(); insert_event( &pool, community, @@ -1860,7 +1860,7 @@ async fn artifact_search_uses_only_live_current_head() { pk, 45010, "artifactneedle old", - Some(home), + None, 1700000000, ) .await; @@ -1871,12 +1871,12 @@ async fn artifact_search_uses_only_live_current_head() { pk, 45010, "artifactneedle current", - Some(home), + None, 1700000001, ) .await; sqlx::query("INSERT INTO artifact_heads(community_id,artifact_id,event_id,channel_id,artifact_type) VALUES($1,$2,$3,$4,'buzz.task')") - .bind(community.as_uuid()).bind(artifact).bind(head.as_slice()).bind(home).execute(&pool).await.unwrap(); + .bind(community.as_uuid()).bind(artifact).bind(head.as_slice()).bind(Uuid::new_v4()).execute(&pool).await.unwrap(); let svc = SearchService::new(pool.clone()); let query = SearchQuery { community, diff --git a/docs/community-artifact-rollout.md b/docs/community-artifact-rollout.md deleted file mode 100644 index a0c0e935688..00000000000 --- a/docs/community-artifact-rollout.md +++ /dev/null @@ -1,111 +0,0 @@ -# Community artifact activation - -Community artifacts implement [NIP-AR](nips/NIP-AR.md). The operator switch -`BUZZ_COMMUNITY_ARTIFACTS_ENABLED` defaults to `false`. Enabling it requires a -restart and a verified contracted schema; setting it on the expand schema -serves channel artifacts but neither accepts nor advertises community scope. - -## Expand and deploy - -For an existing database, apply migration 0097. Deployments that manage -schema out of band can run the same reviewed SQL in a single transaction. -Defer any desired-state plan that changes `artifact_heads` until the guarded -contract below succeeds. The declarative schema specifies the final scoped -primary key, which old channel writers cannot use. - -Migration 0097 adds constant-default scope columns, nullable channel IDs, -community revision JSON, redaction state and a bounded policy map on -`communities`. It retains the `(community_id, artifact_id)` primary key -and adds a scoped unique index. -There is no data backfill. Existing rows default to channel scope. Old channel -writers retain their conflict target and the bridge retains their advisory -lock `artifact:{tenant}:{d}`. All indexes have lock and statement budgets. If -an inline index build exceeds them, leave auto-migration disabled. Apply only -the additive column statements at the top of migration 0097 in a transaction -with the same lock and statement budgets, and commit. Then build the three -indexes with `CREATE [UNIQUE] INDEX CONCURRENTLY` outside a transaction, using -the exact names and column order in 0097. Rerun 0097 to validate their shapes -and record the migration. The additive statements are idempotent for this -procedure; a mismatched column or index still fails closed. - -Deploy this audience-enforcing relay, compatible deletion executors and -operator tools to **every** backend serving the tenant, with the switch off. -Ordinary query, history, ID, search, count, moderation preview and fan-out -fences apply even while the switch is off. Community payloads are stored only -in the existing revision ledger, outside `events` and its generated search -index. They do not enter chat counters, push or hooks. The community purge deletes both scoped ledgers and clears the policy map -before retaining the community tombstone. Compatible deletion executors are -required after contract, alongside serving backends. - -An old binary can continue channel operations on the expanded schema. If -rolling back before contract, disable auto-migration on the old binary: sqlx -otherwise refuses migration versions newer than the binary knows. - -## Separate operator contract - -This step is intentionally absent from automatic migration history. Do not run -it in a migration boot hook. An upgrade skipping the bridge deployment must -stop after expand. After verifying all backends enforce community audiences -and use scoped column inference for upserts, run in one operator session: - -```sh -psql "$DATABASE_URL" -v ON_ERROR_STOP=1 \ - -c "SET buzz.community_artifact_contract_ready = 'all-backends-enforce-community-audience'" \ - -f scripts/maintenance/community-artifact-contract.sql -``` - -The attestation is a human fleet check, not something a database catalog can -prove. The script verifies the expanded unique index and atomically attaches -it as the scoped primary key while removing the legacy primary key, within -5-second lock and 30-second statement budgets. The script is safe to rerun. -After it succeeds, resume desired-state reconciliation for `artifact_heads`. -The declarative schema now matches the scoped primary key. Fresh databases -bootstrapped from `schema/schema.sql` start with that key and require compatible -relay binaries, deletion executors and operator tools from the start. - -Restart compatible backends with `BUZZ_COMMUNITY_ARTIFACTS_ENABLED=true` only -after the fleet check. Each process verifies the scoped primary key, absence -of the old unique key and the expanded columns before accepting writes or -advertising `artifacts.community_scope`. NIP-11 resolves the canonical tenant -UUID and advertises `max_policies: 256`. Verify signed reads and writes in both -scopes, including simultaneous identical `d` values, before allowing clients. - -## Rollback floor - -After contract, this audience-enforcing bridge is the minimum relay version, -even if community writes have not started. Old binaries cannot use their -legacy conflict target. Keep the contracted schema and all privacy fences. -Turning the switch off stops explicit community operations and advertisement; -it does not remove stored payloads or make them ordinary events. Do not restore -the old unique key once both scopes can contain the same `d`. Returning to an -older binary requires a separate reviewed recovery plan and is outside this -activation procedure. No live deployment is part of implementing this feature. - -## Admission and exact-copy lifecycle - -Community admission keeps the authenticated key and its verified owner as -restriction identities. Direct roster membership is sufficient. Owner roster -membership is a fallback only for a verified FI agent assertion or when the -current OA policy permits the verified proof. A timeout blocks new content and -redaction but permits reads and exact accepted-content retries; bans block both. - -| State | Entry and exit fence | -|---|---| -| Subscribe | Claim the subscription generation under the existing lifecycle lock, retain the tenant artifact topic, and confirm Redis interest on one unbroken loss epoch before reading. | -| DB snapshot | Check admission and read current heads in one writer-backed repeatable-read transaction, keyset-paged by identity and indexed by tenant, scope and immutable type. Hold at most 256 heads per page and the advertised set bound overall. | -| Enqueue | Reserve output first. The socket credential gate, subscription generation and pending invalidation are checked before enqueue. | -| Live | A bounded typed Redis signal carries only identity, immutable type and change cause. Check admission and reload the authorized current head on the writer. A denied admission ends the sync with resync. The signal carries no payload. Current-head redaction resyncs that type; historical redaction does not retire its successor. | -| Invalidation | Existing principal/owner disconnect fan-out handles revocation. If an invalidation is missed, an idle sync can retain its set until the next relevant signal or socket revocation. The socket-level revalidator still handles archive, deletion and required-FI upgrades. Decode loss, reconnect or receiver lag resync exact copies. | -| Close | CLOSE, replacement REQ, disconnect and refusal retire the generation, cancel the task and release exactly the topic retained by its scope through the existing teardown. | - -The relay writer pool defaults to 50 connections (`BUZZ_DB_POOL_SIZE`) with a -3 second acquisition timeout. -Community snapshots additionally cap themselves at `min(pool_size - 1, 8)`, -wait at most 1 second for that permit, and refuse one-connection pools. This -leaves a writer slot available when snapshots are paused on output. A -community snapshot or live head read takes one writer checkout with a 2 second -acquisition deadline and a 2 second statement timeout. The existing 30 second -snapshot budget includes paging, enqueue waits and authorization. Other writer -traffic may still saturate the pool; bounded refusal/resync preserves access -control in that case. Ordinary channel sync and ordinary event wire shapes -retain their existing paths. diff --git a/docs/nips/NIP-AR.md b/docs/nips/NIP-AR.md index 531f1b2185b..da0c36a17db 100644 --- a/docs/nips/NIP-AR.md +++ b/docs/nips/NIP-AR.md @@ -1,18 +1,18 @@ NIP-AR ====== -Channel and Community Artifacts -------------------------------- +Channel Artifacts +----------------- `draft` `optional` `relay` -Defines `kind:45010` for editable records called **artifacts**. A channel artifact has one home channel and may be attached to a thread. Its home determines who can read it. The optional [community scope](#community-scoped-artifacts-proposed-extension) has its own audience and no channel home. Any number of artifacts, including of the same type, may share a channel or thread. +Defines `kind:45010` for editable records called **artifacts**. Each artifact has one home channel and may be attached to a thread. Its home determines who can read it. Any number of artifacts, including of the same type, may share a channel or thread. The relay manages identity, access, and revisions. Clients define the content types, such as `buzz.task` or `buzz.project`. ## Event format -Each event contains a complete snapshot. This section defines the channel envelope. This task is created in a channel, with the standard signing fields omitted. +Each event contains a complete snapshot. For example, a task created directly in a channel (standard signing fields omitted): ```json { @@ -52,7 +52,7 @@ Clients place fields needed for filtering in client-defined tags. The relay matc ## Identity and edits -A channel artifact is identified by `(community, d)` within the channel identity space, independently of its author or home. `d` and `type` are immutable. Kind 45010 is a regular stored event, not a NIP-01 addressable event. It falls in Buzz's forum and social kind range (45000–45999) but is not a forum post and follows none of the forum rules. +An artifact is identified by `(community, d)`, independently of its author or home. `d` and `type` are immutable. Kind 45010 is a regular stored event, not a NIP-01 addressable event. It falls in Buzz's forum and social kind range (45000–45999) but is not a forum post and follows none of the forum rules. Creation requires an unused `d`, `op=create`, and no `prev`. Every later revision MUST name the current accepted event in `prev`. The relay checks authorization and advances the current revision atomically: two competing edits cannot both succeed. Timestamps do not choose the winner. @@ -62,11 +62,9 @@ A `create` whose `d` is already in use fails. When the sender cannot read the ex On creation or when changed from the previous accepted revision, `root` MUST identify an existing, undeleted conversation anchor in `h`. Later loss of that anchor does not prevent edits. Replies belong to that conversation, not to an artifact revision. -## Channel access +## Access -This section applies to channel artifacts. Community artifacts follow [Admission and authorization](#admission-and-authorization) instead. - -Channel read permission governs every channel artifact read, including lookups, history, search, previews, counts, and live updates. Threads inherit their channel's audience. Membership and visibility changes take effect on subsequent reads and deliveries. +Channel read permission governs every artifact read, including lookups, history, search, previews, counts, and live updates. Threads inherit their channel's audience. Membership and visibility changes take effect on subsequent reads and deliveries. Write permission means permission to post a kind-9 message in the channel, including authentication, token restrictions, moderation, and archive checks. Relays apply these checks the same way, and at the same point, as for a kind-9 message. This includes agents and, where channel policy permits, nonmembers of open channels. Artifact writes use `messages:write`, the scope that admits kind-9 posting. @@ -134,7 +132,7 @@ sequenceDiagram ["REQ", "s1", {"artifact": "current", "#h": [""], "#type": ["buzz.task"]}] ``` -A channel sync filter MUST include `#h` with 1 or more channels. It accepts the same `#name` predicates and limits as a NIP-AR current-state query, with the same AND/OR rules, and also `kinds: [45010]`. It accepts no `limit` or `offset`. A relay rejects a channel sync filter without `#h`, or any filter with an unknown key, with `CLOSED`. A community sync adds the `scope` key and forbids `#h` instead; see [Reading and syncing](#reading-and-syncing). +The filter MUST include `#h` with 1 or more channels. It accepts the same `#name` predicates and limits as a NIP-AR current-state query, with the same AND/OR rules, and also `kinds: [45010]`. It accepts no `limit` or `offset`. A relay rejects a filter without `#h`, or with an unknown key, with `CLOSED`. **Scope.** The sync's scope is the set of artifacts that a NIP-AR current-state query with the same filter returns to this reader at that time. The rules below use this one definition for access, matching and system channels. @@ -239,69 +237,6 @@ Clients validate content before interpreting it as a known type. Unknown types o Artifact text is untrusted. A type name, relationship tag, or payload cannot authorize a privileged action. Moving, deleting, or revoking access cannot erase copies already downloaded. -## Community-scoped artifacts (proposed extension) - -### Envelope and identity - -A relay advertising `artifacts.community_scope.version = 1` accepts a second form of kind 45010. A community artifact uses `["ar","1"]`, `["community",""]` and the usual `d`, `type`, `title`, `op` and `prev` tags. It MUST omit `h` and `root`. A channel artifact retains its existing envelope and MUST omit the new `community` tag. Reject a missing, mixed or repeated scope. The signed community UUID MUST equal the tenant resolved by the connection or HTTP request, including on retries. Clients obtain this stable UUID from the serving relay's `artifacts.community_scope.community_id` in NIP-11. Two hostnames that serve the same community advertise the same ID. The NIP-11 `artifacts` object advertises the scope: - -```json -"community_scope": {"version": 1, "community_id": "", "max_policies": 256} -``` - -`max_policies` is the bound on stored type policies; this version uses 256. Scope UUIDs on input and output MUST be canonical lowercase, hyphenated, non-nil UUIDs. - -Both scopes reuse the existing head and revision ledger. The identity in a community is `(community, scope class, d)`. Every channel remains in the same channel identity space, so moving a channel artifact preserves its identity. An artifact cannot move between scope classes. Reject `op=move` for a community artifact. In both scopes, `type` is immutable, and a revision naming an identity in the wrong scope answers like an unavailable head. - -For one record per canonical key in a community type, clients MAY derive: - -``` -d = UUIDv8(first 16 bytes of SHA-256( - "nip-ar-community-artifact\0" + community_uuid + "\0" + type + "\0" + key)) -``` - -The inputs are UTF-8. The UUID is lowercase and hyphenated. The type's client contract defines the canonical key, including case and Unicode normalization. Apply the version and variant bits as in the channel derivation. The distinct prefix separates the two derivations. Channel authors can choose arbitrary UUIDs, so the relay MUST also separate the two identity spaces in storage. The same UUID may exist in each scope and cannot reserve a record in the other. Within a scope, the first accepted create reserves the identity. The relay does not interpret names or content, and does not require the key or verify its derivation. - -### Admission and authorization - -| Operation | Required permission | -| --- | --- | -| Read, policy lookup, history, head, or sync | Current effective community admission and `messages:read`. | -| Create, update, delete, or restore | Current effective community admission, `messages:write` and the current write policy for the type. A community timeout blocks the write. | -| Set a type's write policy | A direct community owner or admin acting under `admin:users`. Apply the relay's administrative ban and timeout rules. | - -Apply the same authenticated transport, event signer, expiry, size, quota and moderation rules on HTTP and WebSocket. A channel-restricted credential cannot use community scope, even if it covers every channel. Unauthenticated reads and generic channel permissions confer no community access. Treat lookup failure as denial or an error, with no artifact data. On an open relay, any authenticated principal admitted by current relay rules qualifies under `everyone`, even with no roster row. On a roster relay, the principal needs current effective membership, direct or through verified delegation admitted by the relay. Delegation does not transfer an owner's or admin's role. Apply the principal's and applicable owner's community restrictions. A ban blocks reads and writes, including replay. A timeout leaves reads available. Channel membership, archive, posting restrictions and channel admin roles do not grant or restrict these operations. - -### Type write policy - -The policy is tenant-scoped and keyed by the exact canonical artifact `type`. Missing means `everyone` with no prior policy revision. `admins` admits only an author who personally holds the community owner or admin role. The default on a rosterless open community is still `everyone`. Setting policy requires a configured community owner or admin. - -Use the signed relay-admin command `SET_ARTIFACT_TYPE_POLICY` (proposed kind 9034, pending allocation). Require `community`, `type`, `policy` (`everyone` or `admins`), and `prev` (the current policy command ID or `0` for no prior command). Omit `h` and use empty content. The signed `community` MUST equal the tenant resolved by the request. After verifying the signature, refuse a command signed for another community before consulting any accepted-command record, including on retry, so an admin of several communities cannot apply it to the wrong one. Apply the relay-admin freshness and signer checks. Return a conflict for stale `prev`; an exact retry of the current accepted command is a no-op if the requester is still authorized. A superseded policy command may conflict on retry. Read current policy before retrying a conflicted command. The relay records the accepted admin action in its audit trail. The command is neither a kind 45010 revision nor an event in an ordinary subscription. A client with artifact-signing access alone cannot sign this command through that capability. - -A signed HTTP `/query` policy lookup takes one exact type. For example, `{"artifact":"policy","scope":"community","#type":["example.settings"]}`. It returns `{"policy":"everyone","revision":null}` for an unset type, or the current policy and accepted command ID. The relay advertises and enforces a bound on stored policy entries. At the bound, it rejects a command for a type with no entry, whatever its `policy`, and still accepts changes to existing entries. Switching a configured type back to `everyone` retains its revision, and the entry still counts toward the bound. Retaining the revision prevents an older command from resetting the compare-and-set history. - -A committed policy change governs new revisions, including updates, deletes and restores of existing records. It neither rewrites records nor changes their audience. A write and a policy change MUST be serialized so their admission and commit order agree. Serialize policy updates against write admission before acquiring the artifact's identity lock, including if the type has never had a policy. Recheck the write policy in the transaction. An older pending write that still qualifies must still satisfy the head compare-and-set. An exact previously accepted artifact replay by the same signer, with current community read admission and an unrestricted `messages:write` credential, returns only acknowledgement. It does not re-evaluate the edit policy, timeout or freshness, and it does not write or publish again. This acknowledgement grants no authority to create a new revision. A ban still refuses the replay. Check current community admission and the signed community before consulting receipts. - -### Reading and syncing - -Select the community scope explicitly with `"scope":"community"` on the signed HTTP views `current`, `head` and `history`. For WebSocket sync, use: - -```json -["REQ", "s1", {"artifact":"current","scope":"community","#type":["example.settings"]}] -``` - -This sync selects one exact type and can use the existing exact tag predicates. `#h` is forbidden, and `head` still requires `#d`. Apply admission and scope before any filtering or paging. Reject community-scoped count requests in this version with an explicit error, never a zero or empty count. A legacy filter still sees only channel artifacts. Generic event reads, search, counts, direct ID fetches and ordinary live fan-out MUST exclude community artifact payloads. Route authorized reads through the explicit artifact views. HTTP incremental tokens and deltas remain channel-only in this version. Reject attempts to apply them to community scope. - -Use the same snapshot, buffer bounds, `EOSE` and head sequencing as channel sync. Confirm live interest in the authenticated tenant before opening the snapshot. Only pass change signals to sync, and re-read authorized heads before delivery. A tag or deletion transition follows the existing before-and-after match rule. There is no kind 45011 move removal for community scope. Check current community admission, including any required FI credential, within the initial snapshot and each live head read. When an invalidation or a denied live read reveals loss of access, close the sync with `CLOSED "resync: ..."` or disconnect the session. An idle sync may retain an older set until the next relevant signal or socket revocation. A failed initial read cannot send `EOSE`. After loss of access, the client discards the active set for that community; after re-admission it starts with a fresh complete snapshot. Follow existing sync rules for loss of pub/sub, output and redaction signals. Changing an edit policy alone changes no content or read access. - -### Delete and moderation - -A community soft delete reserves its `d` under the same rules as a channel soft delete. The authorized way to recreate a canonical key is to read its deletion head and send `restore` with that ID in `prev`. A rename to a different key is a create and delete with separate commits. Existing references still address the old identity. A kind-5 deletion cannot target a community artifact revision. - -For community moderation, use a community-bound kind 9005 command with a single target revision `e` and no `h`. Verify that the target is a community-scoped kind 45010 revision in this tenant. Require the existing moderation write scope and direct owner or admin authority, independent of who can edit its type. Redact through the existing moderation path and retain the accepted revision ID. Redaction of a current head ends any affected sync with resync. A kind 9005 with one valid `h` and no `community` uses the existing channel path. Reject repeated, missing or mixed scopes. This command does not emit a channel removal or update chat counters. Deleting the community itself purges both scopes, their acceptance ledgers and the type policies. - -A relay MUST enable community writes and advertise the capability only after all backends that can serve the community enforce the community audience on queries, lookups, moderation and delivery. - ## Incremental reads Incremental reads maintain an eventually consistent local store. They do not prove a complete set at one database snapshot. Absence from a page never proves deletion or loss of access. diff --git a/migrations/0097_community_artifact_expand.sql b/migrations/0097_community_artifact_expand.sql deleted file mode 100644 index 84669e92e39..00000000000 --- a/migrations/0097_community_artifact_expand.sql +++ /dev/null @@ -1,74 +0,0 @@ --- Expand only. Keep the legacy conflict target until every writer and reader --- enforces NIP-AR community audiences. Activation requires the separate, --- guarded operator contract in scripts/maintenance/community-artifact-contract.sql. -SET LOCAL lock_timeout = '5s'; -SET LOCAL statement_timeout = '30s'; - -ALTER TABLE artifact_heads ADD COLUMN IF NOT EXISTS scope TEXT NOT NULL DEFAULT 'channel'; -ALTER TABLE artifact_heads ALTER COLUMN channel_id DROP NOT NULL; -ALTER TABLE artifact_revisions ADD COLUMN IF NOT EXISTS scope TEXT NOT NULL DEFAULT 'channel'; --- Community payloads stay outside the chat/search event store. Channel --- receipts retain their existing event-store payload and wire behavior. -ALTER TABLE artifact_revisions ADD COLUMN IF NOT EXISTS community_event JSONB; -ALTER TABLE artifact_revisions ADD COLUMN IF NOT EXISTS redacted BOOLEAN NOT NULL DEFAULT false; -ALTER TABLE communities ADD COLUMN IF NOT EXISTS artifact_type_policies JSONB NOT NULL DEFAULT '{}'; - --- Small deployments build inline within the budget. Larger deployments may --- prebuild these exact indexes concurrently with auto-migration disabled. -CREATE UNIQUE INDEX IF NOT EXISTS artifact_heads_scoped_identity - ON artifact_heads (community_id, scope, artifact_id); -CREATE INDEX IF NOT EXISTS artifact_revisions_scoped_identity - ON artifact_revisions (community_id, scope, artifact_id); - -CREATE INDEX IF NOT EXISTS artifact_heads_live_type - ON artifact_heads (community_id, scope, artifact_type, artifact_id) WHERE NOT deleted; - -DO $$ -BEGIN - IF (SELECT count(*) FROM (VALUES - ('artifact_heads','scope','text',true), - ('artifact_heads','channel_id','uuid',false), - ('artifact_revisions','scope','text',true), - ('artifact_revisions','community_event','jsonb',false), - ('artifact_revisions','redacted','boolean',true), - ('communities','artifact_type_policies','jsonb',true) - ) expected(rel,col,typ,required) - JOIN pg_attribute a ON a.attrelid=to_regclass(expected.rel) - AND a.attname=expected.col AND NOT a.attisdropped - AND a.atttypid=to_regtype(expected.typ) AND a.attnotnull=expected.required) <> 6 THEN - RAISE EXCEPTION 'community artifact expand column definition mismatch'; - END IF; - IF (SELECT count(*) FROM (VALUES - ('artifact_heads','scope', $default$'channel'::text$default$), - ('artifact_revisions','scope', $default$'channel'::text$default$), - ('artifact_revisions','redacted','false'), - ('communities','artifact_type_policies', $default$'{}'::jsonb$default$) - ) expected(rel,col,expr) - JOIN pg_attribute a ON a.attrelid=to_regclass(expected.rel) AND a.attname=expected.col - JOIN pg_attrdef d ON d.adrelid=a.attrelid AND d.adnum=a.attnum - AND pg_get_expr(d.adbin,d.adrelid)=expected.expr) <> 4 THEN - RAISE EXCEPTION 'community artifact expand default definition mismatch'; - END IF; - IF NOT EXISTS ( - SELECT 1 FROM pg_index i WHERE i.indexrelid='artifact_heads_live_type'::regclass - AND i.indisvalid AND i.indisready AND NOT i.indisunique - AND pg_get_indexdef(i.indexrelid) = 'CREATE INDEX artifact_heads_live_type ON public.artifact_heads USING btree (community_id, scope, artifact_type, artifact_id) WHERE (NOT deleted)' - ) THEN - RAISE EXCEPTION 'community artifact typed index definition mismatch'; - END IF; - IF NOT EXISTS ( - SELECT 1 FROM pg_index i - WHERE i.indexrelid='artifact_heads_scoped_identity'::regclass - AND i.indrelid='artifact_heads'::regclass AND i.indisunique - AND i.indisvalid AND i.indisready AND i.indpred IS NULL AND i.indexprs IS NULL - AND pg_get_indexdef(i.indexrelid) = 'CREATE UNIQUE INDEX artifact_heads_scoped_identity ON public.artifact_heads USING btree (community_id, scope, artifact_id)' - ) OR NOT EXISTS ( - SELECT 1 FROM pg_index i - WHERE i.indexrelid='artifact_revisions_scoped_identity'::regclass - AND i.indrelid='artifact_revisions'::regclass AND NOT i.indisunique - AND i.indisvalid AND i.indisready AND i.indpred IS NULL AND i.indexprs IS NULL - AND pg_get_indexdef(i.indexrelid) = 'CREATE INDEX artifact_revisions_scoped_identity ON public.artifact_revisions USING btree (community_id, scope, artifact_id)' - ) THEN - RAISE EXCEPTION 'community artifact expand index definition mismatch'; - END IF; -END $$; diff --git a/schema/tables/public/artifact_heads.sql b/schema/tables/public/artifact_heads.sql index 6edc6b26bbe..7e73557b9b6 100644 --- a/schema/tables/public/artifact_heads.sql +++ b/schema/tables/public/artifact_heads.sql @@ -1,17 +1,14 @@ -- NIP-AR current heads and acceptance ledger are independent of event retention. --- For an existing database, apply 0097 and complete the guarded contract in --- docs/community-artifact-rollout.md before converging this primary key. CREATE TABLE artifact_heads ( community_id UUID NOT NULL REFERENCES communities(id), artifact_id UUID NOT NULL, - scope TEXT NOT NULL DEFAULT 'channel', event_id BYTEA NOT NULL CHECK (length(event_id) = 32), - channel_id UUID, + channel_id UUID NOT NULL, artifact_type TEXT NOT NULL, root BYTEA, deleted BOOLEAN NOT NULL DEFAULT false, modified_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), - PRIMARY KEY (community_id, scope, artifact_id) + PRIMARY KEY (community_id, artifact_id) ); CREATE INDEX artifact_heads_event ON artifact_heads (community_id, event_id); CREATE INDEX artifact_heads_modified ON artifact_heads (community_id, modified_at, artifact_id); @@ -20,6 +17,3 @@ CREATE INDEX artifact_heads_channel ON artifact_heads (community_id, channel_id, -- The relay does not expire events. Any future row retention or partition -- retirement must skip payloads referenced by `artifact_heads.event_id` -- (NIP-AR: expiring earlier revisions MUST NOT remove the current revision). - -CREATE INDEX artifact_heads_live_type - ON artifact_heads (community_id, scope, artifact_type, artifact_id) WHERE NOT deleted; diff --git a/schema/tables/public/artifact_revisions.sql b/schema/tables/public/artifact_revisions.sql index 285d4cd9247..d3320c0bfff 100644 --- a/schema/tables/public/artifact_revisions.sql +++ b/schema/tables/public/artifact_revisions.sql @@ -4,9 +4,6 @@ CREATE TABLE artifact_revisions ( community_id UUID NOT NULL REFERENCES communities(id), event_id BYTEA NOT NULL CHECK (length(event_id) = 32), artifact_id UUID NOT NULL, - scope TEXT NOT NULL DEFAULT 'channel', - community_event JSONB, - redacted BOOLEAN NOT NULL DEFAULT false, source_channel_id UUID, modified_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), PRIMARY KEY (community_id, event_id) @@ -16,5 +13,3 @@ CREATE INDEX idx_artifact_revisions_artifact ON artifact_revisions (community_id, artifact_id); CREATE INDEX artifact_revisions_moves ON artifact_revisions (community_id, modified_at, event_id) WHERE source_channel_id IS NOT NULL; - -CREATE INDEX artifact_revisions_scoped_identity ON artifact_revisions (community_id, scope, artifact_id); diff --git a/schema/tables/public/communities.sql b/schema/tables/public/communities.sql index 42b220b189a..4c328109f69 100644 --- a/schema/tables/public/communities.sql +++ b/schema/tables/public/communities.sql @@ -26,7 +26,6 @@ CREATE TABLE communities ( deletion_state TEXT NOT NULL DEFAULT 'active' CHECK (deletion_state IN ('active', 'quiescing', 'fenced', 'tombstone')), deletion_fence_generation BIGINT NOT NULL DEFAULT 0 CHECK (deletion_fence_generation >= 0), deleted_at TIMESTAMPTZ, - artifact_type_policies JSONB NOT NULL DEFAULT '{}', artifact_policy_modified_at TIMESTAMPTZ NOT NULL DEFAULT 'epoch', CONSTRAINT chk_communities_id_not_nil CHECK (id <> '00000000-0000-0000-0000-000000000000'::uuid) ); diff --git a/scripts/maintenance/community-artifact-contract.sql b/scripts/maintenance/community-artifact-contract.sql deleted file mode 100644 index 8b8f0e90e12..00000000000 --- a/scripts/maintenance/community-artifact-contract.sql +++ /dev/null @@ -1,43 +0,0 @@ --- OPERATOR CONTRACT, never an automatic migration. Read --- docs/community-artifact-rollout.md before running this file. --- The calling session must explicitly attest that all serving backends, --- deletion executors and operator tools run the compatible audience bridge: --- SET buzz.community_artifact_contract_ready = 'all-backends-enforce-community-audience'; -BEGIN; -SET LOCAL lock_timeout = '5s'; -SET LOCAL statement_timeout = '30s'; -DO $$ -DECLARE - current_key text[]; -BEGIN - IF current_setting('buzz.community_artifact_contract_ready', true) - IS DISTINCT FROM 'all-backends-enforce-community-audience' THEN - RAISE EXCEPTION 'community artifact contract requires explicit fleet compatibility attestation'; - END IF; - SELECT array_agg(a.attname::text ORDER BY k.ord) INTO current_key - FROM pg_index i - CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY k(num,ord) - JOIN pg_attribute a ON a.attrelid=i.indrelid AND a.attnum=k.num - WHERE i.indrelid='artifact_heads'::regclass AND i.indisprimary - AND i.indisvalid AND i.indisready AND i.indpred IS NULL AND i.indexprs IS NULL; - IF current_key = ARRAY['community_id','scope','artifact_id'] THEN - RETURN; -- Already contracted; safe to rerun without touching payloads. - END IF; - IF current_key IS DISTINCT FROM ARRAY['community_id','artifact_id'] THEN - RAISE EXCEPTION 'unexpected artifact head primary key'; - END IF; - IF NOT EXISTS ( - SELECT 1 FROM pg_index i - WHERE i.indexrelid=to_regclass('artifact_heads_scoped_identity') - AND i.indrelid='artifact_heads'::regclass AND i.indisunique - AND i.indisvalid AND i.indisready AND i.indpred IS NULL AND i.indexprs IS NULL - AND pg_get_indexdef(i.indexrelid) = 'CREATE UNIQUE INDEX artifact_heads_scoped_identity ON public.artifact_heads USING btree (community_id, scope, artifact_id)' - ) THEN - RAISE EXCEPTION 'missing or incompatible expanded artifact identity index'; - END IF; - -- Atomic: no interval without a primary key. All key columns are already - -- NOT NULL; attaching the prebuilt index needs no table rewrite or backfill. - ALTER TABLE artifact_heads DROP CONSTRAINT artifact_heads_pkey, - ADD CONSTRAINT artifact_heads_pkey PRIMARY KEY USING INDEX artifact_heads_scoped_identity; -END $$; -COMMIT; From 81dea9c54e3142abba7df255221a75c15193c558 Mon Sep 17 00:00:00 2001 From: Will Pfleger Date: Wed, 18 Nov 2026 21:05:48 -0500 Subject: [PATCH 2/3] fix(relay): keep pending-resync fences on channel artifact sync The reverted change also made channel snapshot and live sends check a pending resync and connection cancellation under the queue lock. Keep those fences so a reader who loses access or sees a redaction while a frame is in flight receives no further payload. Co-authored-by: Paul <4a1bfa0013bc6d14a8d600d8bf6392efefbd2a26ac3c96c9b2a106b0d12297ca@buzz.block.builderlab.xyz> Signed-off-by: Will Pfleger --- .../buzz-relay/src/handlers/artifact_sync.rs | 69 +++++++++++--- .../handlers/artifact_sync_postgres_tests.rs | 90 +++++++++++++++++++ 2 files changed, 149 insertions(+), 10 deletions(-) diff --git a/crates/buzz-relay/src/handlers/artifact_sync.rs b/crates/buzz-relay/src/handlers/artifact_sync.rs index fa0cadf57e2..a03af6aabda 100644 --- a/crates/buzz-relay/src/handlers/artifact_sync.rs +++ b/crates/buzz-relay/src/handlers/artifact_sync.rs @@ -460,8 +460,17 @@ pub async fn handle_sync( // time budget and the cancellation race, so a slow reader cannot hold // the handler slot past the budget or get EOSE after retirement. let initial = async { - let sent = - send_initial_set(&sub_id, owner, &filter, &reader, &mut access, &conn, &state).await?; + let sent = send_initial_set( + &sub_id, + owner, + &filter, + &reader, + &handle, + &mut access, + &conn, + &state, + ) + .await?; // A resync requested before EOSE is queued ends the sync without it. send_eose(&sub_id, owner, &handle, &conn).await?; Ok::<_, Stop>(sent) @@ -587,11 +596,13 @@ async fn confirm(channels: &[Uuid], epoch: u64, conn: &ConnectionState, state: & /// Read and send every head in scope from one snapshot, and return their /// `d`. After an `Err` nothing more is sent. +#[allow(clippy::too_many_arguments)] async fn send_initial_set( sub_id: &str, owner: u64, filter: &ArtifactSyncFilter, reader: &[u8], + handle: &SyncHandle, access: &mut ReadLog, conn: &ConnectionState, state: &AppState, @@ -630,6 +641,7 @@ async fn send_initial_set( owner, RelayMessage::event(sub_id, &stored.event), conn, + Some(handle), ) .await?; access.queued_one(); @@ -647,13 +659,15 @@ async fn send_initial_set( /// during the initial set. The slot is reserved first and the owner checked /// under the lifecycle lock, so the lock is never held while waiting, and a /// CLOSE or replacing REQ (which retire under that lock) fences the frame. +/// With `handle`, a pending resync fences it too. async fn send_owned( sub_id: &str, owner: u64, frame: String, conn: &ConnectionState, + handle: Option<&SyncHandle>, ) -> Result<(), Stop> { - send_reserved(sub_id, owner, frame, None, conn).await + send_reserved(sub_id, owner, frame, handle, conn).await } /// Queue `EOSE` like `send_owned`, unless the sync must resync. The pending @@ -689,7 +703,7 @@ async fn send_reserved( .await .map_err(|_| Stop::Close("error: connection closed"))?; let subs = conn.subscriptions.lock().await; - if !super::close::owns(&subs, sub_id, owner) { + if conn.cancel.is_cancelled() || !super::close::owns(&subs, sub_id, owner) { return Err(Stop::Retired); } let pending = unless_resync.map(|handle| { @@ -712,11 +726,16 @@ async fn try_send_owned( owner: u64, frame: String, conn: &ConnectionState, + handle: Option<&SyncHandle>, ) -> Result<(), Stop> { let subs = conn.subscriptions.lock().await; - if !super::close::owns(&subs, sub_id, owner) { + if conn.cancel.is_cancelled() || !super::close::owns(&subs, sub_id, owner) { return Err(Stop::Retired); } + let pending = handle.map(|h| h.pending.lock().unwrap_or_else(PoisonError::into_inner)); + if let Some(reason) = pending.as_ref().and_then(|p| p.resync) { + return Err(Stop::Close(reason)); + } conn.send_tx .try_send(WsMessage::Text(frame.into())) .map_err(|_| Stop::Close("resync: send queue full")) @@ -785,7 +804,15 @@ async fn run_live( }; #[cfg(test)] super::close::test_seam::pause_at(&test_seam::LIVE_SEND_PAUSE).await; - match try_send_owned(sub_id, owner, RelayMessage::event(sub_id, &event), conn).await { + match try_send_owned( + sub_id, + owner, + RelayMessage::event(sub_id, &event), + conn, + Some(handle), + ) + .await + { Ok(()) => {} Err(Stop::Retired) => return, // One lost frame breaks the copy; the slow-client grace limit @@ -994,20 +1021,42 @@ mod tests { async fn live_frame_is_fenced_by_the_owner() { let (conn, mut rx) = conn_with_sub(1); assert!(matches!( - try_send_owned("s", 2, "x".into(), &conn).await, + try_send_owned("s", 2, "x".into(), &conn, None).await, Err(Stop::Retired) )); conn.subscriptions.lock().await.remove("s"); assert!(matches!( - try_send_owned("s", 1, "x".into(), &conn).await, + try_send_owned("s", 1, "x".into(), &conn, None).await, Err(Stop::Retired) )); assert!(rx.try_recv().is_err()); conn.subscriptions.lock().await.insert("s".into(), held(1)); - assert!(try_send_owned("s", 1, "x".into(), &conn).await.is_ok()); + assert!(try_send_owned("s", 1, "x".into(), &conn, None) + .await + .is_ok()); assert!(rx.try_recv().is_ok()); } + /// A resync recorded after a head read (an access change or redaction + /// signal) fences snapshot and live frames, so nothing more reaches a + /// reader that must resync. Mutation: drop the pending check from + /// `send_reserved` or `try_send_owned` → the frame is queued → RED. + #[tokio::test] + async fn pending_resync_fences_snapshot_and_live_frames() { + let (conn, mut rx) = conn_with_sub(1); + let handle = SyncHandle::new(); + handle.resync("resync: test"); + assert!(matches!( + send_owned("s", 1, "x".into(), &conn, Some(&handle)).await, + Err(Stop::Close("resync: test")) + )); + assert!(matches!( + try_send_owned("s", 1, "x".into(), &conn, Some(&handle)).await, + Err(Stop::Close("resync: test")) + )); + assert!(rx.try_recv().is_err()); + } + /// A frame (such as `EOSE`) waiting for queue room is checked against /// the owner after the room appears, not before it waited. Mutation: /// check the owner before `reserve` → the stale frame is queued → RED. @@ -1020,7 +1069,7 @@ mod tests { .try_send(WsMessage::Text("fill".into())) .unwrap(); } - let mut waiting = std::pin::pin!(send_owned("s", 1, "eose".into(), &conn)); + let mut waiting = std::pin::pin!(send_owned("s", 1, "eose".into(), &conn, None)); // Polled once, the frame is now waiting in `reserve`. assert!(futures_util::poll!(&mut waiting).is_pending()); // A replacing REQ takes the ID while the frame waits. diff --git a/crates/buzz-relay/src/handlers/artifact_sync_postgres_tests.rs b/crates/buzz-relay/src/handlers/artifact_sync_postgres_tests.rs index 9c8e3c5936c..800dec72421 100644 --- a/crates/buzz-relay/src/handlers/artifact_sync_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/artifact_sync_postgres_tests.rs @@ -522,6 +522,96 @@ async fn close_during_a_live_head_read_sends_nothing_more() { no_frame(&mut rx).await; } +/// A resync recorded while a snapshot payload waits for queue room, with the +/// sync still owned, withholds the payload. Mutation: pass `None` instead of +/// the handle from `send_initial_set` → the EVENT is queued → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn resync_while_a_snapshot_payload_waits_sends_no_payload() { + let f = fixture().await; + let owner = Keys::generate(); + let home = create_channel(&f.state, &f.tenant, &owner, &[]).await; + revision(&f, &owner, home, Uuid::new_v4(), "create", None).await; + + let (conn, mut rx) = connect(&f, &owner); + let capacity = conn.send_tx.capacity(); + for _ in 0..capacity { + conn.send_tx + .try_send(WsMessage::Text("fill".into())) + .unwrap(); + } + let task = start_sync(&f, &conn, sync_filter(&[home])); + tokio::time::timeout(Duration::from_secs(10), async { + while !f.state.artifact_syncs.contains(conn.conn_id, "s") { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("sync registered"); + f.state.artifact_syncs.resync_all("resync: test"); + for _ in 0..capacity { + let Some(WsMessage::Text(text)) = rx.recv().await else { + panic!("connection closed"); + }; + assert_eq!(text.as_str(), "fill"); + } + assert_eq!(frame(&mut rx).await, json!(["CLOSED", "s", "resync: test"])); + tokio::time::timeout(Duration::from_secs(5), task) + .await + .expect("sync task ends") + .unwrap(); + no_frame(&mut rx).await; +} + +/// A resync recorded after a live head read, with the sync still owned, +/// withholds the head it read. Mutation: pass `None` instead of the handle +/// from `run_live` → the EVENT precedes `CLOSED` → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn resync_during_a_live_head_read_sends_no_payload() { + let f = fixture().await; + let owner = Keys::generate(); + let home = create_channel(&f.state, &f.tenant, &owner, &[]).await; + let d = Uuid::new_v4(); + let first = revision(&f, &owner, home, d, "create", None).await; + + let (conn, mut rx) = connect(&f, &owner); + let filter = buzz_core::artifact_sync::parse_sync(&sync_filter(&[home])); + let permit = f + .state + .handler_semaphore + .clone() + .try_acquire_owned() + .expect("permit"); + let pause = Arc::new(super::close::test_seam::Pause::default()); + let token = super::close::admit("s", &conn).await.expect("admit"); + let task = tokio::spawn(super::artifact_sync::test_seam::LIVE_SEND_PAUSE.scope( + Arc::clone(&pause), + super::artifact_sync::handle_sync( + "s".into(), + token, + filter, + Arc::clone(&conn), + Arc::clone(&f.state), + permit, + ), + )); + assert_eq!(initial_set(&mut rx).await, vec![first.id.to_hex()]); + + revision(&f, &owner, home, d, "update", Some(&first)).await; + tokio::time::timeout(Duration::from_secs(10), pause.reached.notified()) + .await + .expect("live head read reached"); + f.state.artifact_syncs.resync_all("resync: test"); + pause.resume.notify_one(); + assert_eq!(frame(&mut rx).await, json!(["CLOSED", "s", "resync: test"])); + tokio::time::timeout(Duration::from_secs(5), task) + .await + .expect("sync task ends") + .unwrap(); + no_frame(&mut rx).await; +} + /// Run an ordinary `REQ "s"` through the real handler. async fn ordinary_req(f: &Fixture, conn: &Arc, filters: Vec) { let filters: Vec = filters From 00d41369a92671323cc77470700903caf846e4c8 Mon Sep 17 00:00:00 2001 From: Will Pfleger Date: Wed, 18 Nov 2026 21:13:00 -0500 Subject: [PATCH 3/3] fix(db): keep published migration 0097 in the revert The public main image already shipped 0097, and auto-migrating databases have recorded it; removing the file makes those relays refuse to start. 0097 only adds columns and indexes the channel code ignores, so keep it and declare its expanded shape with the legacy primary key. Co-authored-by: Paul <4a1bfa0013bc6d14a8d600d8bf6392efefbd2a26ac3c96c9b2a106b0d12297ca@buzz.block.builderlab.xyz> Signed-off-by: Will Pfleger --- crates/buzz-db/src/runtime/migration.rs | 2 +- migrations/0097_community_artifact_expand.sql | 74 +++++++++++++++++++ schema/tables/public/artifact_heads.sql | 8 +- schema/tables/public/artifact_revisions.sql | 5 ++ schema/tables/public/communities.sql | 1 + 5 files changed, 88 insertions(+), 2 deletions(-) create mode 100644 migrations/0097_community_artifact_expand.sql diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index bf2e65361ec..cff8a268126 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -879,7 +879,7 @@ mod postgres_tests { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); migrations.sort_by_key(|migration| migration.version); - assert_eq!(migrations.len(), 96); + assert_eq!(migrations.len(), 97); assert_eq!(migrations[89].version, 90); assert!(migrations[89] .sql diff --git a/migrations/0097_community_artifact_expand.sql b/migrations/0097_community_artifact_expand.sql new file mode 100644 index 00000000000..84669e92e39 --- /dev/null +++ b/migrations/0097_community_artifact_expand.sql @@ -0,0 +1,74 @@ +-- Expand only. Keep the legacy conflict target until every writer and reader +-- enforces NIP-AR community audiences. Activation requires the separate, +-- guarded operator contract in scripts/maintenance/community-artifact-contract.sql. +SET LOCAL lock_timeout = '5s'; +SET LOCAL statement_timeout = '30s'; + +ALTER TABLE artifact_heads ADD COLUMN IF NOT EXISTS scope TEXT NOT NULL DEFAULT 'channel'; +ALTER TABLE artifact_heads ALTER COLUMN channel_id DROP NOT NULL; +ALTER TABLE artifact_revisions ADD COLUMN IF NOT EXISTS scope TEXT NOT NULL DEFAULT 'channel'; +-- Community payloads stay outside the chat/search event store. Channel +-- receipts retain their existing event-store payload and wire behavior. +ALTER TABLE artifact_revisions ADD COLUMN IF NOT EXISTS community_event JSONB; +ALTER TABLE artifact_revisions ADD COLUMN IF NOT EXISTS redacted BOOLEAN NOT NULL DEFAULT false; +ALTER TABLE communities ADD COLUMN IF NOT EXISTS artifact_type_policies JSONB NOT NULL DEFAULT '{}'; + +-- Small deployments build inline within the budget. Larger deployments may +-- prebuild these exact indexes concurrently with auto-migration disabled. +CREATE UNIQUE INDEX IF NOT EXISTS artifact_heads_scoped_identity + ON artifact_heads (community_id, scope, artifact_id); +CREATE INDEX IF NOT EXISTS artifact_revisions_scoped_identity + ON artifact_revisions (community_id, scope, artifact_id); + +CREATE INDEX IF NOT EXISTS artifact_heads_live_type + ON artifact_heads (community_id, scope, artifact_type, artifact_id) WHERE NOT deleted; + +DO $$ +BEGIN + IF (SELECT count(*) FROM (VALUES + ('artifact_heads','scope','text',true), + ('artifact_heads','channel_id','uuid',false), + ('artifact_revisions','scope','text',true), + ('artifact_revisions','community_event','jsonb',false), + ('artifact_revisions','redacted','boolean',true), + ('communities','artifact_type_policies','jsonb',true) + ) expected(rel,col,typ,required) + JOIN pg_attribute a ON a.attrelid=to_regclass(expected.rel) + AND a.attname=expected.col AND NOT a.attisdropped + AND a.atttypid=to_regtype(expected.typ) AND a.attnotnull=expected.required) <> 6 THEN + RAISE EXCEPTION 'community artifact expand column definition mismatch'; + END IF; + IF (SELECT count(*) FROM (VALUES + ('artifact_heads','scope', $default$'channel'::text$default$), + ('artifact_revisions','scope', $default$'channel'::text$default$), + ('artifact_revisions','redacted','false'), + ('communities','artifact_type_policies', $default$'{}'::jsonb$default$) + ) expected(rel,col,expr) + JOIN pg_attribute a ON a.attrelid=to_regclass(expected.rel) AND a.attname=expected.col + JOIN pg_attrdef d ON d.adrelid=a.attrelid AND d.adnum=a.attnum + AND pg_get_expr(d.adbin,d.adrelid)=expected.expr) <> 4 THEN + RAISE EXCEPTION 'community artifact expand default definition mismatch'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM pg_index i WHERE i.indexrelid='artifact_heads_live_type'::regclass + AND i.indisvalid AND i.indisready AND NOT i.indisunique + AND pg_get_indexdef(i.indexrelid) = 'CREATE INDEX artifact_heads_live_type ON public.artifact_heads USING btree (community_id, scope, artifact_type, artifact_id) WHERE (NOT deleted)' + ) THEN + RAISE EXCEPTION 'community artifact typed index definition mismatch'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM pg_index i + WHERE i.indexrelid='artifact_heads_scoped_identity'::regclass + AND i.indrelid='artifact_heads'::regclass AND i.indisunique + AND i.indisvalid AND i.indisready AND i.indpred IS NULL AND i.indexprs IS NULL + AND pg_get_indexdef(i.indexrelid) = 'CREATE UNIQUE INDEX artifact_heads_scoped_identity ON public.artifact_heads USING btree (community_id, scope, artifact_id)' + ) OR NOT EXISTS ( + SELECT 1 FROM pg_index i + WHERE i.indexrelid='artifact_revisions_scoped_identity'::regclass + AND i.indrelid='artifact_revisions'::regclass AND NOT i.indisunique + AND i.indisvalid AND i.indisready AND i.indpred IS NULL AND i.indexprs IS NULL + AND pg_get_indexdef(i.indexrelid) = 'CREATE INDEX artifact_revisions_scoped_identity ON public.artifact_revisions USING btree (community_id, scope, artifact_id)' + ) THEN + RAISE EXCEPTION 'community artifact expand index definition mismatch'; + END IF; +END $$; diff --git a/schema/tables/public/artifact_heads.sql b/schema/tables/public/artifact_heads.sql index 7e73557b9b6..a442cb54b17 100644 --- a/schema/tables/public/artifact_heads.sql +++ b/schema/tables/public/artifact_heads.sql @@ -2,14 +2,17 @@ CREATE TABLE artifact_heads ( community_id UUID NOT NULL REFERENCES communities(id), artifact_id UUID NOT NULL, + scope TEXT NOT NULL DEFAULT 'channel', event_id BYTEA NOT NULL CHECK (length(event_id) = 32), - channel_id UUID NOT NULL, + channel_id UUID, artifact_type TEXT NOT NULL, root BYTEA, deleted BOOLEAN NOT NULL DEFAULT false, modified_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), PRIMARY KEY (community_id, artifact_id) ); +CREATE UNIQUE INDEX artifact_heads_scoped_identity + ON artifact_heads (community_id, scope, artifact_id); CREATE INDEX artifact_heads_event ON artifact_heads (community_id, event_id); CREATE INDEX artifact_heads_modified ON artifact_heads (community_id, modified_at, artifact_id); CREATE INDEX artifact_heads_channel ON artifact_heads (community_id, channel_id, artifact_id); @@ -17,3 +20,6 @@ CREATE INDEX artifact_heads_channel ON artifact_heads (community_id, channel_id, -- The relay does not expire events. Any future row retention or partition -- retirement must skip payloads referenced by `artifact_heads.event_id` -- (NIP-AR: expiring earlier revisions MUST NOT remove the current revision). + +CREATE INDEX artifact_heads_live_type + ON artifact_heads (community_id, scope, artifact_type, artifact_id) WHERE NOT deleted; diff --git a/schema/tables/public/artifact_revisions.sql b/schema/tables/public/artifact_revisions.sql index d3320c0bfff..285d4cd9247 100644 --- a/schema/tables/public/artifact_revisions.sql +++ b/schema/tables/public/artifact_revisions.sql @@ -4,6 +4,9 @@ CREATE TABLE artifact_revisions ( community_id UUID NOT NULL REFERENCES communities(id), event_id BYTEA NOT NULL CHECK (length(event_id) = 32), artifact_id UUID NOT NULL, + scope TEXT NOT NULL DEFAULT 'channel', + community_event JSONB, + redacted BOOLEAN NOT NULL DEFAULT false, source_channel_id UUID, modified_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), PRIMARY KEY (community_id, event_id) @@ -13,3 +16,5 @@ CREATE INDEX idx_artifact_revisions_artifact ON artifact_revisions (community_id, artifact_id); CREATE INDEX artifact_revisions_moves ON artifact_revisions (community_id, modified_at, event_id) WHERE source_channel_id IS NOT NULL; + +CREATE INDEX artifact_revisions_scoped_identity ON artifact_revisions (community_id, scope, artifact_id); diff --git a/schema/tables/public/communities.sql b/schema/tables/public/communities.sql index 4c328109f69..42b220b189a 100644 --- a/schema/tables/public/communities.sql +++ b/schema/tables/public/communities.sql @@ -26,6 +26,7 @@ CREATE TABLE communities ( deletion_state TEXT NOT NULL DEFAULT 'active' CHECK (deletion_state IN ('active', 'quiescing', 'fenced', 'tombstone')), deletion_fence_generation BIGINT NOT NULL DEFAULT 0 CHECK (deletion_fence_generation >= 0), deleted_at TIMESTAMPTZ, + artifact_type_policies JSONB NOT NULL DEFAULT '{}', artifact_policy_modified_at TIMESTAMPTZ NOT NULL DEFAULT 'epoch', CONSTRAINT chk_communities_id_not_nil CHECK (id <> '00000000-0000-0000-0000-000000000000'::uuid) );