From be8138f9d8602dc28267cee47020885403496f7f Mon Sep 17 00:00:00 2001 From: Krish Ray Date: Tue, 17 Nov 2026 21:00:45 -0500 Subject: [PATCH 1/3] docs(protocol): propose community-scoped NIP-AR artifacts Add a proposed extension to NIP-AR for kind 45010 artifacts scoped to a whole community instead of a home channel: a signed community tag, an explicit query scope, a separate identity space, and a per-type write policy set by community owners and admins through a relay-admin command. Documentation only. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Krish Ray --- docs/nips/NIP-AR.md | 75 +++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 69 insertions(+), 6 deletions(-) diff --git a/docs/nips/NIP-AR.md b/docs/nips/NIP-AR.md index da0c36a17db..9e8b72f94d5 100644 --- a/docs/nips/NIP-AR.md +++ b/docs/nips/NIP-AR.md @@ -1,18 +1,18 @@ NIP-AR ====== -Channel Artifacts ------------------ +Channel and Community Artifacts +------------------------------- `draft` `optional` `relay` -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. +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. 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. For example, a task created directly in a channel (standard signing fields omitted): +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. ```json { @@ -52,7 +52,7 @@ Clients place fields needed for filtering in client-defined tags. The relay matc ## Identity and edits -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. +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. 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,7 +62,7 @@ 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. -## Access +## Channel access 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. @@ -237,6 +237,69 @@ 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; the value shown is an example. + +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, count, 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. 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. Switching a configured type back to `everyone` retains its revision. + +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. Take the same policy lock before 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. 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 on signed HTTP views `current`, `head` and `history`. For example: + +```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, counting or paging. 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. Recheck current access outside the old snapshot before sending pages, `EOSE` and live heads. An authorization change invalidating the sync MUST close it with `CLOSED "resync: ..."` or disconnect the session if that is how the relay revokes access. This includes changes in direct or delegated membership, community admission mode, bans, and credential revocation. End the sync on a failed recheck. A failed or revoked 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. 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. From 27a4c8a86e9e9795bfaf5fe59f35164a6389a9ed Mon Sep 17 00:00:00 2001 From: Krish Ray Date: Tue, 17 Nov 2026 21:06:33 -0500 Subject: [PATCH 2/3] docs(protocol): scope channel rules, bind policy command to its community Co-Authored-By: Claude Opus 5.5 Signed-off-by: Krish Ray --- docs/nips/NIP-AR.md | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/docs/nips/NIP-AR.md b/docs/nips/NIP-AR.md index 9e8b72f94d5..ddf13659f52 100644 --- a/docs/nips/NIP-AR.md +++ b/docs/nips/NIP-AR.md @@ -64,7 +64,9 @@ On creation or when changed from the previous accepted revision, `root` MUST ide ## Channel access -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. +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. 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. @@ -132,7 +134,7 @@ sequenceDiagram ["REQ", "s1", {"artifact": "current", "#h": [""], "#type": ["buzz.task"]}] ``` -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`. +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). **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. @@ -264,7 +266,7 @@ The inputs are UTF-8. The UUID is lowercase and hyphenated. The type's client co | Operation | Required permission | | --- | --- | -| Read, count, policy lookup, history, head, or sync | Current effective community admission and `messages:read`. | +| 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. | @@ -274,21 +276,21 @@ Apply the same authenticated transport, event signer, expiry, size, quota and mo 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. 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. +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. Switching a configured type back to `everyone` retains its revision. +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. 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. Take the same policy lock before 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. 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 on signed HTTP views `current`, `head` and `history`. For example: +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, counting or paging. 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. +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. Recheck current access outside the old snapshot before sending pages, `EOSE` and live heads. An authorization change invalidating the sync MUST close it with `CLOSED "resync: ..."` or disconnect the session if that is how the relay revokes access. This includes changes in direct or delegated membership, community admission mode, bans, and credential revocation. End the sync on a failed recheck. A failed or revoked 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. From 956cb8f87e30462b4309c82e477a694dc1d3a023 Mon Sep 17 00:00:00 2001 From: Krish Ray Date: Wed, 18 Nov 2026 01:24:46 -0500 Subject: [PATCH 3/3] feat(relay): support community-scoped NIP-AR artifacts Bind community-scoped artifacts and type policies to the signed tenant. Reuse NIP-AR revision receipts and exact sync with scoped notifications, current community admission, and an explicit shape for policy reads. Expand the head key while preserving old channel writers, then require an operator step before advertising the new scope. Exercise signed HTTP and WebSocket behavior, cluster delivery, and both rollout stages. Co-authored-by: Codex Signed-off-by: Krish Ray --- .env.example | 4 + crates/buzz-audit/src/service.rs | 22 +- crates/buzz-core/src/artifact.rs | 303 +++++++- 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 | 2 +- crates/buzz-db/src/runtime/mod.rs | 21 + crates/buzz-db/src/store/admin_moderation.rs | 1 + crates/buzz-db/src/store/artifact.rs | 28 +- .../src/store/artifact_postgres_tests.rs | 517 +++++++++++++ crates/buzz-db/src/store/artifact_query.rs | 19 +- crates/buzz-db/src/store/artifact_sync.rs | 6 +- .../buzz-db/src/store/community_artifact.rs | 681 ++++++++++++++++++ crates/buzz-db/src/store/deletion.rs | 37 +- crates/buzz-db/src/store/event.rs | 35 +- crates/buzz-db/src/store/mod.rs | 2 + 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 + .../examples/community_artifact_probe.rs | 397 ++++++++++ crates/buzz-relay/src/api/admin/mod.rs | 38 +- .../artifact_direct_postgres_tests.rs | 59 ++ crates/buzz-relay/src/api/artifact.rs | 69 +- .../src/api/artifact_postgres_tests.rs | 29 +- .../community_postgres_tests.rs | 390 ++++++++++ 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 | 2 +- .../buzz-relay/src/handlers/artifact_sync.rs | 394 ++++++++-- .../artifact_sync/community_access.rs | 74 ++ .../handlers/artifact_sync_postgres_tests.rs | 2 + .../community_postgres_tests.rs | 681 ++++++++++++++++++ crates/buzz-relay/src/handlers/close.rs | 6 + .../src/handlers/community_artifact.rs | 338 +++++++++ crates/buzz-relay/src/handlers/event.rs | 37 +- crates/buzz-relay/src/handlers/ingest.rs | 82 ++- crates/buzz-relay/src/handlers/mod.rs | 2 + .../buzz-relay/src/handlers/side_effects.rs | 7 +- crates/buzz-relay/src/main.rs | 5 + crates/buzz-relay/src/nip11.rs | 8 + crates/buzz-relay/src/protocol.rs | 2 + crates/buzz-relay/src/state.rs | 4 + crates/buzz-relay/src/subscription.rs | 18 +- crates/buzz-search/src/query.rs | 3 +- .../tests/postgres_fts_integration.rs | 8 +- docs/community-artifact-rollout.md | 107 +++ docs/nips/NIP-AR.md | 8 +- 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 + .../community-artifact-contract.sql | 43 ++ 56 files changed, 4654 insertions(+), 174 deletions(-) create mode 100644 crates/buzz-db/src/store/community_artifact.rs create mode 100644 crates/buzz-pubsub/src/artifact_signal.rs create mode 100644 crates/buzz-relay/examples/community_artifact_probe.rs create mode 100644 crates/buzz-relay/src/api/admin/postgres_tests/artifact_direct_postgres_tests.rs create mode 100644 crates/buzz-relay/src/api/artifact_postgres_tests/community_postgres_tests.rs create mode 100644 crates/buzz-relay/src/handlers/artifact_sync/community_access.rs create mode 100644 crates/buzz-relay/src/handlers/artifact_sync_postgres_tests/community_postgres_tests.rs create mode 100644 crates/buzz-relay/src/handlers/community_artifact.rs create mode 100644 docs/community-artifact-rollout.md create mode 100644 migrations/0097_community_artifact_expand.sql create mode 100644 scripts/maintenance/community-artifact-contract.sql diff --git a/.env.example b/.env.example index e99896d9faf..63e16a1baf5 100644 --- a/.env.example +++ b/.env.example @@ -502,3 +502,7 @@ 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 3d2cb8d3648..13385220f24 100644 --- a/crates/buzz-audit/src/service.rs +++ b/crates/buzz-audit/src/service.rs @@ -54,10 +54,24 @@ 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 @@ -71,7 +85,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 { @@ -119,11 +133,9 @@ 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 50e8f6070db..6d49b180c0c 100644 --- a/crates/buzz-core/src/artifact.rs +++ b/crates/buzz-core/src/artifact.rs @@ -41,13 +41,37 @@ 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, +} +impl ArtifactScope { + /// Stable storage discriminator. + pub fn as_str(self) -> &'static str { + match self { + Self::Channel => "channel", + Self::Community => "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, - /// Home channel. - pub home: 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, /// Immutable type name. pub artifact_type: String, /// Lifecycle operation. @@ -84,7 +108,17 @@ pub fn validate(event: &Event) -> Result { if event.tags.len() > MAX_TAGS { return Err("too many tags"); } - let names = ["ar", "d", "h", "type", "title", "op", "root", "prev"]; + let names = [ + "ar", + "d", + "h", + "community", + "type", + "title", + "op", + "root", + "prev", + ]; let mut fields = std::collections::HashMap::new(); let mut bytes = 0; for tag in event.tags.iter() { @@ -120,20 +154,24 @@ pub fn validate(event: &Event) -> Result { return Err("unsupported artifact envelope version"); } let id = canonical_uuid(field("d")?)?; - let home = canonical_uuid(field("h")?)?; + 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 artifact_type = field("type")?; - 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"); - } + 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"); + } 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"); @@ -158,6 +196,8 @@ pub fn validate(event: &Event) -> Result { } Ok(ArtifactEnvelope { id, + scope, + community, home, artifact_type: artifact_type.into(), op, @@ -232,6 +272,7 @@ 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(_)), @@ -283,11 +324,15 @@ 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. @@ -316,6 +361,9 @@ 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)))) @@ -339,9 +387,20 @@ 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 tags = parse_predicates(object, &["artifact", "kinds", "limit", "offset"])?; + 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 number = |name: &str, default: u64| { object .get(name) @@ -354,10 +413,13 @@ pub fn parse_query(value: &serde_json::Value) -> Result MAX_PAGE_SIZE as u64 || offset > MAX_OFFSET { return Err("artifact page limit exceeded"); } - if view != ArtifactView::Current && !tags.iter().any(|(n, _)| n == "d") { + if matches!(view, ArtifactView::Head | ArtifactView::History) + && !tags.iter().any(|(n, _)| n == "d") + { return Err("history and head require #d"); } Ok(ArtifactQuery { + scope, view, tags, limit: limit as i64, @@ -407,3 +469,210 @@ 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 87f63d417eb..bbcb8b6605b 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, parse_predicates}; +use crate::artifact::{canonical_uuid, exact_type, parse_predicates, parse_scope, ArtifactScope}; use uuid::Uuid; /// Largest set one sync serves: it bounds each initial read and the held @@ -12,6 +12,8 @@ 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). @@ -48,7 +50,19 @@ 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 106b46eda36..3369665cf81 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_auth, deletion, dm, entity_deletion, event, feed, - git_repo, leader_lock, media, membership_snapshot, moderation, nip_fi_binding, + channel_members, community, community_artifact, 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 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/crates/buzz-db/src/runtime/mod.rs b/crates/buzz-db/src/runtime/mod.rs index ebe7fb4a3f4..de12c606601 100644 --- a/crates/buzz-db/src/runtime/mod.rs +++ b/crates/buzz-db/src/runtime/mod.rs @@ -267,6 +267,9 @@ 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`]). @@ -843,6 +846,12 @@ 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, @@ -1390,6 +1399,12 @@ 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(), @@ -1413,6 +1428,12 @@ 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 a3a7e8c00e5..b72f7aa390c 100644 --- a/crates/buzz-db/src/store/admin_moderation.rs +++ b/crates/buzz-db/src/store/admin_moderation.rs @@ -555,6 +555,7 @@ pub async fn get_event_preview( 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 tags @> '[["community"]]'::jsonb)) AND NOT (kind = 5 AND EXISTS ( SELECT 1 FROM jsonb_array_elements(tags) t WHERE t->>0 = 'k' AND t->>1 = ANY($4::text[]))) diff --git a/crates/buzz-db/src/store/artifact.rs b/crates/buzz-db/src/store/artifact.rs index 6f9f46eb174..02bb1ee7c14 100644 --- a/crates/buzz-db/src/store/artifact.rs +++ b/crates/buzz-db/src/store/artifact.rs @@ -4,7 +4,7 @@ //! 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}; +use buzz_core::artifact::{ArtifactEnvelope, ArtifactOp, ArtifactScope}; use buzz_core::{CommunityId, StoredEvent}; use nostr::{Event, EventBuilder, Keys, Kind, Tag}; use sqlx::Row; @@ -82,7 +82,7 @@ impl Db { ) .await?; Ok(sqlx::query_scalar( - "SELECT channel_id FROM artifact_heads WHERE community_id=$1 AND artifact_id=$2", + "SELECT channel_id FROM artifact_heads WHERE community_id=$1 AND scope='channel' AND artifact_id=$2", ) .bind(community.as_uuid()) .bind(artifact) @@ -102,6 +102,12 @@ 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()) @@ -122,7 +128,7 @@ impl Db { 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 artifact_id=$2 FOR UPDATE", + "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", ) .bind(community.as_uuid()) .bind(env.id) @@ -145,7 +151,7 @@ impl Db { if source != match op { ArtifactOp::Move => authorized_source, - _ => Some(env.home), + _ => Some(home), } => { return Ok(ArtifactOutcome::Conflict(HEAD_UNAVAILABLE)) @@ -163,7 +169,7 @@ impl Db { "deleted artifacts require restore; live artifacts cannot restore", )); } - if (op == ArtifactOp::Move) != (source != Some(env.home)) { + if (op == ArtifactOp::Move) != (source != Some(home)) { return Ok(ArtifactOutcome::Rejected( "only move changes home and move must change home", )); @@ -173,10 +179,10 @@ impl Db { } } } - if head.is_none() || env.root != old_root || source != Some(env.home) { + if head.is_none() || env.root != old_root || source != Some(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(env.home).fetch_one(tx.conn()).await?; + .bind(community.as_uuid()).bind(root).bind(home).fetch_one(tx.conn()).await?; if !exists { return Ok(ArtifactOutcome::Rejected( "root must be an existing conversation anchor in home", @@ -193,11 +199,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,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?; + 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?; let (stored, _) = - 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?; + crate::event::insert_event_in_transaction(&mut tx, event, Some(home)).await?; + crate::insert_mentions_in_transaction(&mut tx, event, Some(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 f858deeb182..f55b5b4faf1 100644 --- a/crates/buzz-db/src/store/artifact_postgres_tests.rs +++ b/crates/buzz-db/src/store/artifact_postgres_tests.rs @@ -823,3 +823,520 @@ 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 serde_json::json; + + async fn contract(f: &Fixture) { + assert!(!f.db.community_artifact_schema_ready().await.unwrap()); + 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, + } + } + 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 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(_) + )); + 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()); + } + + /// 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()); + } + + /// The enqueue guard shares the restriction-writer lock and member row + /// locks: a revocation commits on one side of the guarded enqueue, never + /// between its admission check and queue point. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn read_guard_serializes_committed_revocation() { + let f = Fixture::new().await; + // One snapshot in a two-slot pool must leave room for fresh admission. + // A second snapshot sheds instead of taking the last writer slot. + 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!(tokio::time::timeout( + std::time::Duration::from_secs(2), + small.open_community_artifact_snapshot(f.community, &open) + ) + .await + .unwrap() + .is_err()); + small + .community_artifact_read_guard(f.community, &open) + .await + .unwrap() + .finish() + .await + .unwrap(); + snapshot.finish().await.unwrap(); + let one = Db::from_pool( + sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .connect(&crate::test_support::database_url()) + .await + .unwrap(), + ); + assert!(one + .open_community_artifact_snapshot(f.community, &open) + .await + .is_err()); + role(&f, &f.peer, "member").await; + let reader = principal(&f.peer, true); + let guard = + f.db.community_artifact_read_guard(f.community, &reader) + .await + .unwrap(); + let pool = f.db.pool.clone(); + let community = f.community; + let key = f.peer.public_key().to_hex(); + let removal = tokio::spawn(async move { + sqlx::query("DELETE FROM relay_members WHERE community_id=$1 AND pubkey=$2") + .bind(community.as_uuid()) + .bind(key) + .execute(&pool) + .await + .unwrap(); + }); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + assert!(!removal.is_finished()); + guard.finish().await.unwrap(); + removal.await.unwrap(); + assert!(f + .db + .community_artifact_read_guard(f.community, &reader) + .await + .is_err()); + role(&f, &f.peer, "member").await; + role(&f, &f.owner, "owner").await; + let guard = + f.db.community_artifact_read_guard(f.community, &reader) + .await + .unwrap(); + let pool = f.db.pool.clone(); + let archive = tokio::spawn(async move { + sqlx::query("UPDATE communities SET archived_at=clock_timestamp() WHERE id=$1") + .bind(community.as_uuid()) + .execute(&pool) + .await + .unwrap(); + }); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + assert!( + !archive.is_finished(), + "archive cannot commit before guarded enqueue" + ); + guard.finish().await.unwrap(); + archive.await.unwrap(); + let open_reader = principal(&f.peer, false); + assert!(f + .db + .community_artifact_read_guard(f.community, &open_reader) + .await + .is_err()); + 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()); + } + /// 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 unset_policy_lock_serializes_artifact_admission() { + let f = Fixture::new().await; + contract(&f).await; + role(&f, &f.owner, "owner").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 db = f.db.clone(); + let community = f.community; + let peer = principal(&f.peer, false); + let pending = tokio::spawn(async move { + db.accept_community_artifact(community, &peer, &event, &env) + .await + }); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + assert!( + !pending.is_finished(), + "artifact bypassed the type policy transaction" + ); + tx.commit().await.unwrap(); + assert!( + pending.await.unwrap().is_err(), + "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 9a5cee1bc4f..96a7e016a92 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 NOT a.deleted "); + 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 "); } ArtifactView::Head => { - qb.push("JOIN artifact_heads a ON a.community_id=e.community_id AND a.event_id=e.id "); + qb.push("JOIN artifact_heads a ON a.community_id=e.community_id AND a.event_id=e.id AND a.scope='channel' "); } - ArtifactView::History => {} + ArtifactView::History | ArtifactView::Policy => {} } push_scope( qb, @@ -62,7 +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 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 NOT e.tags @> '[[\"community\"]]'::jsonb 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()) @@ -158,7 +158,7 @@ impl ArtifactSnapshot { 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 "); + 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, @@ -196,6 +196,13 @@ 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'") @@ -235,7 +242,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.artifact_id=") + 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=") .push_bind(artifact) .push(" "); push_scope(&mut qb, community, reader, &[], named_channels.to_vec()); diff --git a/crates/buzz-db/src/store/artifact_sync.rs b/crates/buzz-db/src/store/artifact_sync.rs index 4da01728fd0..f802024a406 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.modified_at >= COALESCE($3::timestamptz,'epoch'::timestamptz) + WHERE a.community_id=$1 AND a.scope='channel' 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.community_id=m.community_id AND a.channel_id=m.channel_id + ON a.scope='channel' AND 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 + FROM artifact_revisions r WHERE r.community_id=$1 AND r.scope='channel' 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 new file mode 100644 index 00000000000..6e6684b7d17 --- /dev/null +++ b/crates/buzz-db/src/store/community_artifact.rs @@ -0,0 +1,681 @@ +//! 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::{ArtifactOutcome, HEAD_UNAVAILABLE}; +use crate::{Db, DbError, Result}; +use buzz_core::artifact::{ + 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, +} + +fn denied() -> DbError { + DbError::AccessDenied("community artifact access denied".into()) +} + +/// Serialize with existing ban, timeout and ownership writers. Membership rows +/// are also share-locked, so a removal cannot commit between this check and a +/// guarded enqueue. Shared reads do not serialize readers with each other. +async fn authorize( + conn: &mut PgConnection, + community: CommunityId, + principal: &CommunityArtifactPrincipal, +) -> Result { + sqlx::query("SET LOCAL statement_timeout='2s'") + .execute(&mut *conn) + .await?; + sqlx::query("SET LOCAL lock_timeout='2s'") + .execute(&mut *conn) + .await?; + sqlx::query( + "SELECT pg_advisory_xact_lock_shared(hashtextextended('invite-admission:' || $1::text,0))", + ) + .bind(community.as_uuid()) + .execute(&mut *conn) + .await?; + let direct: Option = sqlx::query_scalar( + "SELECT role FROM relay_members WHERE community_id=$1 AND pubkey=$2 FOR SHARE", + ) + .bind(community.as_uuid()) + .bind(hex::encode(&principal.pubkey)) + .fetch_optional(&mut *conn) + .await?; + let delegated = if let Some(owner) = principal + .verified_owner + .as_ref() + .filter(|_| principal.owner_admission) + { + sqlx::query_scalar::<_, String>( + "SELECT role FROM relay_members WHERE community_id=$1 AND pubkey=$2 FOR SHARE", + ) + .bind(community.as_uuid()) + .bind(hex::encode(owner)) + .fetch_optional(&mut *conn) + .await? + .is_some() + } 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, +} + +/// A fresh authorization transaction held through a response's queue point. +/// Its locks serialize that queue point with committed admission revocations. +pub struct CommunityArtifactReadGuard { + tx: Transaction<'static, Postgres>, + requires_nip_fi: bool, +} +impl CommunityArtifactReadGuard { + /// Current stored authentication requirement, protected through enqueue. + pub fn requires_nip_fi(&self) -> bool { + self.requires_nip_fi + } + + /// Release read-admission locks after the protected enqueue. + pub async fn finish(self) -> Result<()> { + self.tx.commit().await?; + Ok(()) + } +} + +// SHARE conflicts with archive/auth-policy writers' NO KEY UPDATE lock, while +// allowing readers together. Writers take their type lock before this row; +// policy commands use UPDATE directly, avoiding shared-lock upgrade deadlocks. +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) +} + +async fn policy_lock( + conn: &mut PgConnection, + community: CommunityId, + artifact_type: &str, +) -> Result<()> { + sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))") + .bind(format!("artifact-policy:{community}:{artifact_type}")) + .execute(conn) + .await?; + Ok(()) +} + +/// 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()); + } + crate::deletion::guard_community_write(tx, community).await?; + let authority = authorize(tx, community, principal).await?; + // Relay-admin commands retain administrative authority during a content + // timeout. authorize still refuses the principal's and applicable owner's + // bans; new artifact revisions separately enforce their content timeout. + if !authority.admin { + return Err(denied()); + } + policy_lock(tx, community, &command.artifact_type).await?; + 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 UPDATE") + .bind(community.as_uuid()) + .fetch_optional(&mut **tx) + .await? + .ok_or_else(denied)?; + let current = policy_value(&state, &command.artifact_type)?; + // Bans and current direct authority precede command receipts, matching + // the shared relay-admin gate (content timeouts do not block commands). + 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?) + } + /// Fresh writer-backed audience admission held through the caller's enqueue. + pub async fn community_artifact_read_guard( + &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 = Transaction::begin(connection, None).await?; + sqlx::raw_sql("SET LOCAL statement_timeout='2s'; SET LOCAL lock_timeout='2s'") + .execute(&mut *tx) + .await?; + crate::deletion::guard_community_write(&mut tx, community).await?; + authorize(&mut tx, community, principal).await?; + let requires_nip_fi = lock_active_community(&mut tx, community).await?; + Ok(CommunityArtifactReadGuard { + tx, + requires_nip_fi, + }) + } + /// 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 guard = self + .community_artifact_read_guard(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 *guard.tx) + .await?; + let policy = policy_value(&state, artifact_type)?; + guard.finish().await?; + Ok(policy) + } + /// Exact accepted replay needs admission and tenant binding, never new edit + /// authority. The durable ledger survives redaction and deletion payloads. + pub async fn community_artifact_accepted( + &self, + community: CommunityId, + principal: &CommunityArtifactPrincipal, + event: &Event, + ) -> Result { + let envelope = buzz_core::artifact::validate(event).map_err(|_| denied())?; + if envelope.scope != ArtifactScope::Community + || envelope.community != Some(*community.as_uuid()) + || event.pubkey.as_bytes().as_slice() != principal.pubkey + { + return Err(denied()); + } + let mut guard = self + .community_artifact_read_guard(community, principal) + .await?; + let accepted=sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM artifact_revisions WHERE community_id=$1 AND scope='community' AND event_id=$2)") + .bind(community.as_uuid()).bind(event.id.as_bytes().as_slice()).fetch_one(&mut *guard.tx).await?; + guard.finish().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 { + if env.scope != ArtifactScope::Community + || env.community != Some(*community.as_uuid()) + || event.pubkey.as_bytes().as_slice() != principal.pubkey + { + return Err(denied()); + } + let mut tx = self.begin_event_write_transaction(community).await?; + let authority = authorize(tx.conn(), community, principal).await?; + policy_lock(tx.conn(), community, &env.artifact_type).await?; + lock_active_community(tx.conn(), community).await?; + sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))") + .bind(format!("artifact:{community}:community:{}", env.id)) + .execute(tx.conn()) + .await?; + if sqlx::query_scalar::<_,bool>("SELECT EXISTS(SELECT 1 FROM artifact_revisions WHERE community_id=$1 AND scope='community' AND event_id=$2)") + .bind(community.as_uuid()).bind(event.id.as_bytes().as_slice()).fetch_one(tx.conn()).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?; + 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)), + (Some(head), op) => { + if env.prev.as_deref() != Some(head.try_get::, _>("event_id")?.as_slice()) { + return Ok(ArtifactOutcome::Conflict("artifact head changed")); + } + if head.try_get::("artifact_type")? != env.artifact_type { + return Ok(ArtifactOutcome::Rejected("artifact type is immutable")); + } + if head.try_get::("deleted")? != (op == ArtifactOp::Restore) { + return Ok(ArtifactOutcome::Rejected( + "deleted artifacts require restore; live artifacts cannot restore", + )); + } + } + } + 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 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::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 view != ArtifactView::History && name == "d" { + let ids: Vec = values.iter().filter_map(|v| v.parse().ok()).collect(); + qb.push(" AND a.artifact_id=ANY(").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 +} +fn rows_to_events(rows: Vec) -> Result> { + rows.into_iter() + .map(|row| { + 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, + )) + }) + .collect() +} +/// One repeatable-read cut of community heads; the sync uses the same keyset +/// paging, buffer bounds, budget and complete-set enqueue protocol as channels. +pub struct CommunityArtifactSnapshot { + tx: Transaction<'static, Postgres>, + _permit: tokio::sync::OwnedSemaphorePermit, + community: CommunityId, + after: Option, + done: bool, +} +impl CommunityArtifactSnapshot { + /// Read one keyset page in this snapshot. + pub async fn next_page( + &mut self, + tags: &[(String, Vec)], + page: i64, + ) -> Result> { + if self.done { + return Ok(vec![]); + } + let mut qb = query_builder(self.community, ArtifactView::Current, tags); + if let Some(after) = self.after { + qb.push(" AND a.artifact_id>").push_bind(after); + } + qb.push(" ORDER BY a.artifact_id LIMIT ").push_bind(page); + let rows = qb.build().fetch_all(&mut *self.tx).await?; + self.done = (rows.len() as i64) < page; + if let Some(last) = rows.last() { + self.after = Some(last.try_get("artifact_id")?); + } + rows_to_events(rows) + } + /// End the complete-set snapshot. + pub async fn finish(self) -> Result<()> { + self.tx.commit().await?; + Ok(()) + } +} +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 guard = self + .community_artifact_read_guard(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 *guard.tx).await?)?; + guard.finish().await?; + Ok(events) + } + /// Open a community complete-set snapshot on the writer, after live interest. + /// Current admission is checked outside it before every enqueue. + pub async fn open_community_artifact_snapshot( + &self, + community: CommunityId, + principal: &CommunityArtifactPrincipal, + ) -> Result { + // Admission is bounded independently of the 30 s snapshot budget. + // A pool with one slot cannot hold a snapshot and recheck admission. + 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)?; + self.community_artifact_read_guard(community, principal) + .await? + .finish() + .await?; + 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 = 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(CommunityArtifactSnapshot { + _permit: permit, + tx, + community, + after: None, + done: false, + }) + } + /// 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 query = ArtifactQuery { + scope: ArtifactScope::Community, + view: ArtifactView::Head, + tags: vec![("d".into(), vec![id.to_string()])], + limit: 1, + offset: 0, + }; + Ok(self + .query_community_artifacts(community, principal, &query) + .await? + .into_iter() + .next() + .map(|head| { + let deleted = head + .event + .tags + .iter() + .any(|tag| tag.as_slice() == ["op", "delete"]); + (head, deleted) + })) + } + /// 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?; + let authority = authorize(tx.conn(), community, principal).await?; + if !authority.admin || authority.timed_out { + return Err(denied()); + } + lock_active_community(tx.conn(), community).await?; + 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) + } +} + +impl Db { + /// Node-wide idle-sync backstop: check at most 256 distinct principals in + /// one writer query. This never reads content and never grants delivery; + /// every actual enqueue still takes a current authorization guard. + pub async fn community_artifact_admission_batch( + &self, + community: CommunityId, + principals: &[CommunityArtifactPrincipal], + ) -> Result> { + if principals.len() > 256 { + return Err(DbError::InvalidData("admission batch too large".into())); + } + let keys: Vec> = principals.iter().map(|p| p.pubkey.clone()).collect(); + let owners: Vec> = principals + .iter() + .map(|p| p.verified_owner.clone().unwrap_or_default()) + .collect(); + let require: Vec = principals.iter().map(|p| p.require_membership).collect(); + let owner_admission: Vec = principals.iter().map(|p| p.owner_admission).collect(); + 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 = Transaction::begin(connection, None).await?; + sqlx::query("SET LOCAL statement_timeout='2s'") + .execute(&mut *tx) + .await?; + let allowed=sqlx::query_as("SELECT COALESCE((SELECT requires_nip_fi FROM communities WHERE id=$1),true), EXISTS(SELECT 1 FROM communities c WHERE c.id=$1 AND c.deletion_state='active' AND c.archived_at IS NULL) AND (NOT p.roster OR EXISTS(SELECT 1 FROM relay_members m WHERE m.community_id=$1 AND (m.pubkey=encode(p.key,'hex') OR (p.owner_admission AND m.pubkey=encode(p.owner,'hex'))))) AND NOT EXISTS(SELECT 1 FROM community_bans b WHERE b.community_id=$1 AND b.banned AND (b.ban_expires_at IS NULL OR b.ban_expires_at>clock_timestamp()) AND b.pubkey IN (SELECT p.key UNION ALL SELECT p.owner UNION ALL SELECT u.agent_owner_pubkey FROM users u WHERE u.community_id=$1 AND u.pubkey=p.key)) FROM unnest($2::bytea[],$3::bytea[],$4::boolean[],$5::boolean[]) WITH ORDINALITY p(key,owner,roster,owner_admission,ord) ORDER BY p.ord") + .bind(community.as_uuid()).bind(keys).bind(owners).bind(require).bind(owner_admission).fetch_all(&mut *tx).await?; + tx.commit().await?; + Ok(allowed) + } +} diff --git a/crates/buzz-db/src/store/deletion.rs b/crates/buzz-db/src/store/deletion.rs index 490d53cf6ad..fec04ac0121 100644 --- a/crates/buzz-db/src/store/deletion.rs +++ b/crates/buzz-db/src/store/deletion.rs @@ -2448,7 +2448,8 @@ 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 deletion_fence_generation = $2 \ + AND COALESCE(to_jsonb(communities)->'artifact_type_policies' = '{}'::jsonb, true))", ) .bind(token.community_id.as_uuid()) .bind(generation) @@ -3485,6 +3486,15 @@ 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, \ @@ -9130,6 +9140,16 @@ 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 @@ -9243,6 +9263,20 @@ 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", @@ -9572,6 +9606,7 @@ 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 5828698286b..d5d728f3437 100644 --- a/crates/buzz-db/src/store/event.rs +++ b/crates/buzz-db/src/store/event.rs @@ -746,6 +746,7 @@ fn build_query_events_sql( // Use unqualified column names when no join, qualified when joined. let col_prefix = if q.p_tag_hex.is_some() { "e." } else { "" }; + push_community_artifact_exclusion(&mut qb, col_prefix); push_event_filters(&mut qb, col_prefix, q); // A per-channel read scopes each lateral to one channel of the set. if per_channel.is_some() { @@ -783,11 +784,12 @@ 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))")); + 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'))")); } push_notice_visibility(qb, col_prefix, q); @@ -1496,6 +1498,17 @@ 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) @@ -1599,11 +1612,12 @@ 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))")); + 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'))")); } push_notice_visibility(&mut qb, col_prefix, q); @@ -1796,7 +1810,7 @@ pub(crate) async fn get_event_by_id_with_operation( let mut connection = crate::observability::acquire_writer(pool, operation).await?; 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 deleted_at IS NULL ORDER BY created_at DESC LIMIT 1", + FROM events WHERE community_id = $1 AND id = $2 AND (kind <> 45010 OR (channel_id IS NOT NULL AND NOT tags @> '[[\"community\"]]'::jsonb)) AND deleted_at IS NULL ORDER BY created_at DESC LIMIT 1", ) .bind(community_id.as_uuid()) .bind(id_bytes) @@ -1873,7 +1887,7 @@ pub(crate) async fn get_event_by_id_including_deleted_with_operation( let mut connection = crate::observability::acquire_writer(pool, operation).await?; 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 ORDER BY created_at DESC LIMIT 1", + FROM events WHERE community_id = $1 AND id = $2 AND (kind <> 45010 OR (channel_id IS NOT NULL AND NOT tags @> '[[\"community\"]]'::jsonb)) ORDER BY created_at DESC LIMIT 1", ) .bind(community_id.as_uuid()) .bind(id_bytes) @@ -1933,6 +1947,7 @@ 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 { @@ -3047,7 +3062,10 @@ mod e_tag_filter_shape_tests { assert!(sql.starts_with("WITH m AS MATERIALIZED (SELECT ")); assert_eq!(sql.matches("tags @> ANY(").count(), 1); - assert!(!sql.contains(" OR ")); + // 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 @>")); let fence_end = sql.find(") SELECT * FROM m ").expect("fence closes"); assert!(sql.contains("::jsonb[])")); assert!(!sql[..fence_end].contains("ORDER BY")); @@ -7196,3 +7214,10 @@ 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) { + qb.push(format!(" AND ({prefix}kind <> 45010 OR ({prefix}channel_id IS NOT NULL AND NOT {prefix}tags @> '[[\"community\"]]'::jsonb))")); +} diff --git a/crates/buzz-db/src/store/mod.rs b/crates/buzz-db/src/store/mod.rs index e9c2e0d72bb..2a97d00edbe 100644 --- a/crates/buzz-db/src/store/mod.rs +++ b/crates/buzz-db/src/store/mod.rs @@ -95,6 +95,8 @@ 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/tests/observability_source.rs b/crates/buzz-db/tests/observability_source.rs index f85af28be13..7b75dae59bd 100644 --- a/crates/buzz-db/tests/observability_source.rs +++ b/crates/buzz-db/tests/observability_source.rs @@ -4068,6 +4068,7 @@ 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 new file mode 100644 index 00000000000..4e994ab8f2e --- /dev/null +++ b/crates/buzz-pubsub/src/artifact_signal.rs @@ -0,0 +1,59 @@ +//! 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 e7f85d53801..38fc825ba7a 100644 --- a/crates/buzz-pubsub/src/lib.rs +++ b/crates/buzz-pubsub/src/lib.rs @@ -21,6 +21,8 @@ //! 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. @@ -137,6 +139,7 @@ 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, @@ -155,6 +158,7 @@ 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); @@ -169,6 +173,7 @@ 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, @@ -189,6 +194,7 @@ 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(), @@ -240,6 +246,22 @@ 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`. @@ -516,7 +538,7 @@ mod tests { use super::*; use crate::test_util::make_test_pool; use buzz_core::{CommunityId, TenantContext}; - use nostr::{EventBuilder, Keys, Kind}; + use nostr::{EventBuilder, JsonUtil, Keys, Kind}; use uuid::Uuid; async fn make_manager() -> Arc { @@ -539,8 +561,8 @@ mod tests { let mut rx = manager.subscribe_local(); let manager_clone = manager.clone(); - tokio::spawn(async move { manager_clone.run_subscriber().await }); - tokio::time::sleep(tokio::time::Duration::from_millis(200)).await; + let subscriber = tokio::spawn(async move { manager_clone.run_subscriber().await }); + manager.link_state().wait_for(|link| link.up).await.unwrap(); let ctx = ctx(0xaaaa, "a.example"); let channel_id = Uuid::new_v4(); @@ -554,6 +576,10 @@ 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) @@ -568,6 +594,53 @@ 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 49cd27417d3..1d814cb5d2b 100644 --- a/crates/buzz-pubsub/src/subscriber.rs +++ b/crates/buzz-pubsub/src/subscriber.rs @@ -49,6 +49,7 @@ 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, @@ -60,6 +61,7 @@ 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, @@ -95,6 +97,7 @@ 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, @@ -187,6 +190,18 @@ 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 07cabf9eca5..6666221b05d 100644 --- a/crates/buzz-pubsub/src/topic.rs +++ b/crates/buzz-pubsub/src/topic.rs @@ -19,6 +19,8 @@ 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. @@ -46,6 +48,9 @@ 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) + } } } @@ -71,6 +76,7 @@ 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/examples/community_artifact_probe.rs b/crates/buzz-relay/examples/community_artifact_probe.rs new file mode 100644 index 00000000000..c9beaac93ae --- /dev/null +++ b/crates/buzz-relay/examples/community_artifact_probe.rs @@ -0,0 +1,397 @@ +//! Local-only signed HTTP/WS NIP-AR integration probe. Run against an ephemeral +//! relay configured with the public test key 1 as its owner. Never use test keys +//! for a real community. See docs/community-artifact-rollout.md. +use base64::Engine; +use futures_util::{SinkExt, StreamExt}; +use nostr::{Event, EventBuilder, Keys, Kind, Tag}; +use serde_json::{json, Value}; +use sha2::Digest; +use std::time::Duration; +use uuid::Uuid; +type Result = std::result::Result>; + +fn sign(keys: &Keys, kind: u16, tags: Vec>, content: &str) -> Result { + Ok(EventBuilder::new(Kind::Custom(kind), content) + .tags( + tags.into_iter() + .map(Tag::parse) + .collect::, _>>()?, + ) + .sign_with_keys(keys)?) +} +async fn post( + client: &reqwest::Client, + base: &str, + keys: &Keys, + path: &str, + body: Value, +) -> Result<(bool, Value)> { + let bytes = serde_json::to_vec(&body)?; + let auth = sign( + keys, + 27235, + vec![ + vec!["u".into(), format!("{base}{path}")], + vec!["method".into(), "POST".into()], + vec!["payload".into(), hex::encode(sha2::Sha256::digest(&bytes))], + vec!["nonce".into(), Uuid::new_v4().to_string()], + ], + "", + )?; + let response = client + .post(format!("{base}{path}")) + .header("content-type", "application/json") + .header( + "authorization", + format!( + "Nostr {}", + base64::engine::general_purpose::STANDARD.encode(serde_json::to_vec(&auth)?) + ), + ) + .body(bytes) + .send() + .await?; + let success = response.status().is_success(); + Ok((success, response.json().await?)) +} +async fn publish(client: &reqwest::Client, base: &str, keys: &Keys, event: &Event) -> Result<()> { + let (ok, body) = post(client, base, keys, "/events", json!(event)).await?; + if !ok || body["accepted"] != true { + return Err(format!("publish failed: {body}").into()); + } + Ok(()) +} +fn revision(keys: &Keys, scope: &str, id: &str, d: Uuid, prev: Option<&Event>) -> Result { + let mut tags = vec![ + vec!["ar".into(), "1".into()], + vec![scope.into(), id.into()], + vec!["d".into(), d.to_string()], + vec!["type".into(), "example.settings".into()], + vec!["title".into(), "Probe".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()]); + } + sign(keys, 45010, tags, "private probe payload") +} +/// Exercise the unchanged channel wire protocol on expand and contract, also +/// against the previous relay binary. No community capability is required. +async fn channel_compat(client: &reqwest::Client, base: &str) -> Result<()> { + let owner = Keys::parse(&format!("{:064x}", 1))?; + let homes = [Uuid::new_v4(), Uuid::new_v4()]; + for home in homes { + let event = sign( + &owner, + 9007, + vec![ + vec!["h".into(), home.to_string()], + vec!["name".into(), format!("compat-{home}")], + ], + "", + )?; + publish(client, base, &owner, &event).await?; + } + let d = Uuid::new_v4(); + let first = revision(&owner, "h", &homes[0].to_string(), d, None)?; + publish(client, base, &owner, &first).await?; + let update = revision(&owner, "h", &homes[0].to_string(), d, Some(&first))?; + publish(client, base, &owner, &update).await?; + publish(client, base, &owner, &first).await?; + let (ok, heads) = post( + client, + base, + &owner, + "/query", + json!([{"artifact":"current","#d":[d]}]), + ) + .await?; + assert!(ok); + assert_eq!(heads, json!([update])); + let moved = sign( + &owner, + 45010, + vec![ + vec!["ar".into(), "1".into()], + vec!["h".into(), homes[1].to_string()], + vec!["d".into(), d.to_string()], + vec!["type".into(), "example.settings".into()], + vec!["title".into(), "Moved probe".into()], + vec!["op".into(), "move".into()], + vec!["prev".into(), update.id.to_hex()], + ], + "moved probe payload", + )?; + publish(client, base, &owner, &moved).await?; + let (ok, heads) = post( + client, + base, + &owner, + "/query", + json!([{"artifact":"head","#d":[d]}]), + ) + .await?; + assert!(ok); + assert_eq!(heads, json!([moved])); + let (ok, history) = post( + client, + base, + &owner, + "/query", + json!([{"artifact":"history","#d":[d]}]), + ) + .await?; + assert!(ok); + let history = history.as_array().ok_or("history array")?; + assert_eq!(history.len(), 3); + for event in [&first, &update, &moved] { + assert!( + history.contains(&json!(event)), + "exact signed channel event preserved" + ); + } + println!("PASS: exact signed channel create/update/replay/move/head/history wire output"); + Ok(()) +} +async fn next( + socket: &mut tokio_tungstenite::WebSocketStream< + tokio_tungstenite::MaybeTlsStream, + >, +) -> Result { + loop { + let message = tokio::time::timeout(Duration::from_secs(10), socket.next()) + .await? + .ok_or("socket ended")??; + if let tokio_tungstenite::tungstenite::Message::Text(text) = message { + return Ok(serde_json::from_str(&text)?); + } + } +} +#[tokio::main] +async fn main() -> Result<()> { + let base = std::env::args() + .nth(1) + .ok_or("usage: community_artifact_probe http://localhost:3030 [--expect-disabled | --channel-only]")?; + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(10)) + .build()?; + let info: Value = client + .get(&base) + .header("accept", "application/nostr+json") + .send() + .await? + .json() + .await?; + if std::env::args().any(|s| s == "--expect-disabled") { + assert!(info["artifacts"].get("community_scope").is_none()); + println!("PASS: community capability withheld on expand/disabled schema"); + return channel_compat(&client, &base).await; + } + if std::env::args().any(|s| s == "--channel-only") { + return channel_compat(&client, &base).await; + } + let capability = &info["artifacts"]["community_scope"]; + assert_eq!(capability["version"], 1); + assert_eq!(capability["max_policies"], 256); + let community = capability["community_id"] + .as_str() + .ok_or("community capability missing")?; + assert_eq!(Uuid::parse_str(community)?.to_string(), community); + let owner = Keys::parse(&format!("{:064x}", 1))?; + let peer = Keys::parse(&format!("{:064x}", 2))?; + let (ok, policy) = post( + &client, + &base, + &owner, + "/query", + json!([{"artifact":"policy","scope":"community","#type":["example.settings"]}]), + ) + .await?; + assert!(ok); + let mut policy_prev = policy["revision"].as_str().unwrap_or("0").to_owned(); + if policy["policy"] != "everyone" { + let reset = sign( + &owner, + 9034, + vec![ + vec!["community".into(), community.into()], + vec!["type".into(), "example.settings".into()], + vec!["policy".into(), "everyone".into()], + vec!["prev".into(), policy_prev], + ], + "", + )?; + publish(&client, &base, &owner, &reset).await?; + policy_prev = reset.id.to_hex(); + } + let d = Uuid::new_v4(); + let first = revision(&peer, "community", community, d, None)?; + publish(&client, &base, &peer, &first).await?; + let current = json!([{"artifact":"current","scope":"community","#type":["example.settings"]}]); + let (ok, heads) = post(&client, &base, &peer, "/query", current.clone()).await?; + assert!(ok); + assert!(heads + .as_array() + .ok_or("heads array")? + .iter() + .any(|e| e["id"] == first.id.to_hex())); + let unsigned = client + .post(format!("{base}/query")) + .json(¤t) + .send() + .await?; + assert!(!unsigned.status().is_success()); + let ws_url = base.replacen("http", "ws", 1); + let (mut ws, _) = tokio_tungstenite::connect_async(&ws_url).await?; + let challenge = loop { + let message = next(&mut ws).await?; + if message[0] == "AUTH" { + break message[1].as_str().ok_or("challenge")?.to_owned(); + } + }; + let auth = sign( + &peer, + 22242, + vec![ + vec!["relay".into(), ws_url], + vec!["challenge".into(), challenge], + ], + "", + )?; + ws.send(tokio_tungstenite::tungstenite::Message::Text( + json!(["AUTH", auth]).to_string().into(), + )) + .await?; + loop { + let message = next(&mut ws).await?; + if message[0] == "OK" { + assert_eq!(message[2], true); + break; + } + } + ws.send(tokio_tungstenite::tungstenite::Message::Text( + json!(["REQ","s1",{"artifact":"current","scope":"community","#type":["example.settings"]}]) + .to_string() + .into(), + )) + .await?; + let mut seen = false; + loop { + let message = next(&mut ws).await?; + match message[0].as_str() { + Some("EVENT") => seen |= message[2]["id"] == first.id.to_hex(), + Some("EOSE") => break, + _ => return Err(format!("unexpected snapshot frame {message}").into()), + } + } + assert!(seen); + let update = revision(&peer, "community", community, d, Some(&first))?; + publish(&client, &base, &peer, &update).await?; + let message = next(&mut ws).await?; + assert_eq!(message[0], "EVENT"); + assert_eq!(message[2]["id"], update.id.to_hex()); + let command = sign( + &owner, + 9034, + vec![ + vec!["community".into(), community.into()], + vec!["type".into(), "example.settings".into()], + vec!["policy".into(), "admins".into()], + vec!["prev".into(), policy_prev], + ], + "", + )?; + publish(&client, &base, &owner, &command).await?; + publish(&client, &base, &owner, &command).await?; + publish(&client, &base, &peer, &first).await?; + let refused = revision(&peer, "community", community, d, Some(&update))?; + assert!( + !post(&client, &base, &peer, "/events", json!(refused)) + .await? + .0 + ); + let wrong = revision( + &peer, + "community", + &Uuid::new_v4().to_string(), + Uuid::new_v4(), + None, + )?; + assert!( + !post(&client, &base, &peer, "/events", json!(wrong)) + .await? + .0 + ); + for filter in [ + json!({"ids":[update.id.to_hex()]}), + json!({"kinds":[45010],"search":"probe"}), + json!({"kinds":[45010]}), + ] { + let (ok, body) = post(&client, &base, &peer, "/query", json!([filter])).await?; + assert!(ok); + let events = body.as_array().ok_or("generic events array")?; + for event in events { + assert_ne!(event["id"], update.id.to_hex()); + assert!(event["tags"] + .as_array() + .ok_or("event tags")? + .iter() + .all(|tag| tag[0] != "community")); + } + } + assert!( + !post(&client, &base, &peer, "/count", current.clone()) + .await? + .0 + ); + let home = Uuid::new_v4(); + let create = sign( + &owner, + 9007, + vec![ + vec!["h".into(), home.to_string()], + vec!["name".into(), format!("probe-{home}")], + ], + "", + )?; + publish(&client, &base, &owner, &create).await?; + let channel = revision(&owner, "h", &home.to_string(), d, None)?; + publish(&client, &base, &owner, &channel).await?; + let (ok, body) = post( + &client, + &base, + &peer, + "/query", + json!([{"artifact":"current","#d":[d]}]), + ) + .await?; + assert!(ok); + assert_eq!(body[0]["id"], channel.id.to_hex()); + let redaction = sign( + &owner, + 9005, + vec![ + vec!["community".into(), community.into()], + vec!["e".into(), update.id.to_hex()], + ], + "", + )?; + publish(&client, &base, &owner, &redaction).await?; + let message = next(&mut ws).await?; + assert_eq!(message[0], "CLOSED"); + assert!(message[2] + .as_str() + .ok_or("closed reason")? + .starts_with("resync:")); + publish(&client, &base, &peer, &update).await?; + ws.close(None).await?; + println!("PASS: signed HTTP and NIP-42 WS snapshot/live, policy CAS replay, wrong tenant, privacy, same-d channel collision, and redaction/resync"); + Ok(()) +} diff --git a/crates/buzz-relay/src/api/admin/mod.rs b/crates/buzz-relay/src/api/admin/mod.rs index c29797185b6..14f9777763e 100644 --- a/crates/buzz-relay/src/api/admin/mod.rs +++ b/crates/buzz-relay/src/api/admin/mod.rs @@ -1498,6 +1498,7 @@ 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::{ @@ -12006,43 +12007,6 @@ 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 new file mode 100644 index 00000000000..f478f21901d --- /dev/null +++ b/crates/buzz-relay/src/api/admin/postgres_tests/artifact_direct_postgres_tests.rs @@ -0,0 +1,59 @@ +//! 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 7284563be8b..4f1a834db3b 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, - reader: &nostr::PublicKey, + caller: &super::bridge::ProvenCaller, 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, reader, filters, count).await) + Some(execute(state, tenant, caller, filters, count).await) } Err(reason) => { routed(); @@ -46,10 +46,11 @@ pub(super) async fn query( async fn execute( state: &Arc, tenant: &TenantContext, - reader: &nostr::PublicKey, + caller: &super::bridge::ProvenCaller, 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 { @@ -69,6 +70,59 @@ 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, + }; + 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 @@ -95,3 +149,12 @@ 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 2519510cf4c..66bdfce4654 100644 --- a/crates/buzz-relay/src/api/artifact_postgres_tests.rs +++ b/crates/buzz-relay/src/api/artifact_postgres_tests.rs @@ -308,7 +308,9 @@ async fn lifecycle_routes_duplicate_replay_delete_and_redaction() { EventBuilder::new(Kind::Custom(kind), "") .tags([ Tag::parse(["e", &restore.id.to_hex()]).unwrap(), - Tag::parse(["h", &f.home.to_string()]).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(), ]) .sign_with_keys(&f.owner) .unwrap() @@ -320,6 +322,28 @@ 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]}]); @@ -489,3 +513,6 @@ 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 new file mode 100644 index 00000000000..cdd2784bf65 --- /dev/null +++ b/crates/buzz-relay/src/api/artifact_postgres_tests/community_postgres_tests.rs @@ -0,0 +1,390 @@ +//! 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()); + 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; + 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(); + let command = policy(&f, "admins", None); + accepted(&f, &f.owner, &command).await; + accepted(&f, &f.owner, &command).await; + 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 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(); + 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()); +} + +/// 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 8b50f748939..f0c6eab8427 100644 --- a/crates/buzz-relay/src/api/artifact_sync.rs +++ b/crates/buzz-relay/src/api/artifact_sync.rs @@ -151,7 +151,9 @@ 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 { + if parsed.view != ArtifactView::Current + || parsed.scope != buzz_core::artifact::ArtifactScope::Channel + { 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 09909496174..ac98ad4648f 100644 --- a/crates/buzz-relay/src/api/bridge.rs +++ b/crates/buzz-relay/src/api/bridge.rs @@ -109,6 +109,8 @@ 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, } @@ -128,6 +130,7 @@ impl ProvenCaller { event_id_bytes, signed_at, token_owner, + artifact_owner: None, slot: slot.clone(), } } @@ -1464,17 +1467,25 @@ async fn submit_event_authed( token_owner, ) .await; - if let Err(e) = caller.admit_member(membership) { - return SubmitOutcome::Err { - response: e.into_response(), - }; - } + let artifact_owner = match caller.admit_member(membership) { + Ok(owner) => owner.or(token_owner), + Err(e) => { + 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: crate::handlers::ingest::HttpAuthMethod::Nip98, - }; + 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); // Typing indicators are ephemeral: broadcast to the channel, never stored. let result = if is_typing { @@ -1624,8 +1635,9 @@ 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)); + 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()) + }); // NIP-FI admission. [FI-TRACE-AUTHORITY-UNIFORM] let proof = crate::nip_fi_shadow::EnforcedProof::new(&state, &headers, "bridge"); @@ -1699,7 +1711,7 @@ async fn query_events_authed( caller.token_owner, ) .await; - caller + caller.artifact_owner = caller .admit_member(membership) .map_err(IntoResponse::into_response)?; @@ -1734,7 +1746,7 @@ async fn query_member_events( } let routed = || caller.read_artifact(&raw_filters); if let Some(result) = - super::artifact::query(state, tenant, &pubkey, &raw_filters, false, routed).await + super::artifact::query(state, tenant, caller, &raw_filters, false, routed).await { return result; } @@ -2397,7 +2409,7 @@ async fn count_events_authed( caller.token_owner, ) .await; - caller + caller.artifact_owner = caller .admit_member(membership) .map_err(IntoResponse::into_response)?; @@ -2418,7 +2430,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, &pubkey, &raw, true, routed).await { + if let Some(result) = super::artifact::query(state, tenant, caller, &raw, true, routed).await { return result; } let filters: Vec = serde_json::from_slice(body) @@ -3494,6 +3506,7 @@ 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); @@ -11314,6 +11327,7 @@ 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, @@ -11493,6 +11507,7 @@ 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 4f91dfa75b2..e6be69d5bc2 100644 --- a/crates/buzz-relay/src/config.rs +++ b/crates/buzz-relay/src/config.rs @@ -185,6 +185,8 @@ 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. @@ -1548,6 +1550,16 @@ 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 c52e71d6d4d..33f2ca78be8 100644 --- a/crates/buzz-relay/src/handlers/artifact.rs +++ b/crates/buzz-relay/src/handlers/artifact.rs @@ -88,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; } -fn verify_revision_auth(event: &Event) -> Result<(), IngestError> { +pub(super) 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 fa0cadf57e2..a34b7c6b2ec 100644 --- a/crates/buzz-relay/src/handlers/artifact_sync.rs +++ b/crates/buzz-relay/src/handlers/artifact_sync.rs @@ -4,6 +4,9 @@ //! says that one `d` changed; the sync task then reads that artifact's current //! head and sends it (NIP-AR Sync rules 3 and 4). Any possible loss of a live //! entry ends the sync with `CLOSED "resync: ..."` (rule 5). +mod community_access; +pub use community_access::watch as watch_community_access; + use std::collections::{HashMap, HashSet}; use std::sync::{Arc, Mutex as StdMutex, PoisonError}; use std::time::Duration; @@ -11,7 +14,8 @@ 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::StoredEvent; +use buzz_core::{artifact::ArtifactScope, CommunityId, StoredEvent}; +use buzz_db::community_artifact::CommunityArtifactPrincipal; use buzz_pubsub::EventTopic; use dashmap::DashMap; use nostr::{Alphabet, Event, Filter, JsonUtil, Kind, SingleLetterTag}; @@ -102,9 +106,18 @@ 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, + connection: std::sync::Weak, +} + /// 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, @@ -113,6 +126,7 @@ pub struct SyncHandle { impl SyncHandle { fn new() -> Self { Self { + community: None, pending: StdMutex::new(Pending::default()), notify: Notify::new(), cancel: CancellationToken::new(), @@ -194,6 +208,46 @@ 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 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() { @@ -271,6 +325,27 @@ impl ArtifactSyncs { } } +/// Consume typed metadata from the existing Redis subscriber. A lag is a +/// possible gap and ends exact copies; ordinary ChannelEvent never carries it. +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_all("resync: live delivery lagged"), + Err(tokio::sync::broadcast::error::RecvError::Closed) => { + state.artifact_syncs.resync_all("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. @@ -382,9 +457,11 @@ 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) = match conn.auth_state_snapshot() { + let (reader, bound, delegated_owner) = match conn.auth_state_snapshot() { AuthState::Authenticated(ctx) => { - if !ctx.scopes.is_empty() && !ctx.scopes.contains(&Scope::MessagesRead) { + if (filter.scope == ArtifactScope::Community || !ctx.scopes.is_empty()) + && !ctx.scopes.contains(&Scope::MessagesRead) + { super::close::close_if_owner( &sub_id, owner, @@ -399,14 +476,20 @@ 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.channels.iter().any(|id| !allowed.contains(id)) { + if filter.scope == ArtifactScope::Community + || 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.pubkey.to_bytes().to_vec(), + ctx.channel_ids, + ctx.agent_owner_pubkey, + ) } _ => { super::close::close_if_owner( @@ -439,11 +522,50 @@ 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 handle = Arc::new(SyncHandle::new()); - let Some(owner) = claim(&sub_id, owner, &filter.channels, &handle, &conn, &state).await else { + 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; + } + 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()), + connection: Arc::downgrade(&conn), + 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, + }, + }); + } + let handle = Arc::new(handle); + let Some(owner) = claim(&sub_id, owner, &filter, &handle, &conn, &state).await else { return; }; - if !start.up || !confirm(&filter.channels, start.epoch, &conn, &state).await { + if !start.up || !confirm(&filter, start.epoch, &conn, &state).await { close( &sub_id, owner, @@ -460,10 +582,19 @@ 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, + &mut access, + &conn, + &state, + &handle, + ) + .await?; // A resync requested before EOSE is queued ends the sync without it. - send_eose(&sub_id, owner, &handle, &conn).await?; + send_eose(&sub_id, owner, &handle, &conn, Some(&state)).await?; Ok::<_, Stop>(sent) }; let outcome = tokio::select! { @@ -535,7 +666,7 @@ enum Stop { async fn claim( sub_id: &str, owner: u64, - channels: &[Uuid], + filter: &ArtifactSyncFilter, handle: &Arc, conn: &ConnectionState, state: &AppState, @@ -548,6 +679,23 @@ 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, @@ -566,9 +714,17 @@ 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(channels: &[Uuid], epoch: u64, conn: &ConnectionState, state: &AppState) -> bool { +async fn confirm( + filter: &ArtifactSyncFilter, + epoch: u64, + conn: &ConnectionState, + state: &AppState, +) -> bool { let confirm_all = async { - for &channel in channels { + 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 { match state .pubsub .confirm_topic(&conn.tenant, EventTopic::Channel(channel)) @@ -587,6 +743,7 @@ 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, @@ -595,17 +752,28 @@ async fn send_initial_set( access: &mut ReadLog, conn: &ConnectionState, state: &AppState, + handle: &SyncHandle, ) -> Result, Stop> { - 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 snapshot = if let Some(interest) = &handle.community { + Snapshot::Community( + state + .db + .open_community_artifact_snapshot(conn.tenant.community(), &interest.principal) + .await + .map_err(|_| Stop::Close(RESTRICTED))?, + ) + } else { + match state + .db + .open_artifact_snapshot(conn.tenant.community(), reader, &filter.channels) + .await + { + Ok(Ok(snapshot)) => Snapshot::Channel(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(); @@ -630,6 +798,8 @@ async fn send_initial_set( owner, RelayMessage::event(sub_id, &stored.event), conn, + Some(handle), + Some(state), ) .await?; access.queued_one(); @@ -652,8 +822,10 @@ async fn send_owned( owner: u64, frame: String, conn: &ConnectionState, + handle: Option<&SyncHandle>, + state: Option<&AppState>, ) -> Result<(), Stop> { - send_reserved(sub_id, owner, frame, None, conn).await + send_reserved(sub_id, owner, frame, handle, conn, state).await } /// Queue `EOSE` like `send_owned`, unless the sync must resync. The pending @@ -665,6 +837,7 @@ async fn send_eose( owner: u64, handle: &SyncHandle, conn: &ConnectionState, + state: Option<&AppState>, ) -> Result<(), Stop> { send_reserved( sub_id, @@ -672,6 +845,7 @@ async fn send_eose( RelayMessage::eose(sub_id), Some(handle), conn, + state, ) .await } @@ -682,14 +856,20 @@ 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; + // Reserve output first, then recheck authoritative access outside the old + // snapshot. Keep its locks through enqueue, including after a slow reader. + let _guard = current_guard(unless_resync, state, conn).await?; 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,14 +892,120 @@ 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 _guard = current_guard(handle, state, conn).await?; 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); } - conn.send_tx - .try_send(WsMessage::Text(frame.into())) - .map_err(|_| Stop::Close("resync: send queue full")) + 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(()) +} +/// Current auth is held until the frame reaches the outbound queue. An empty +/// channel set is never treated as community authorization. +struct QueueGuard { + _database: buzz_db::community_artifact::CommunityArtifactReadGuard, + _effect: crate::nip_fi_gate::SessionEffectPermit, +} +async fn current_guard( + 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 Some(state) = state else { + return Err(Stop::Close("resync: access check unavailable")); + }; + if !community_credential_current(state, conn, &interest.principal) { + return Err(Stop::Close("resync: community access changed")); + } + let effect = conn + .nip_fi_gate + .acquire_effect() + .await + .map_err(|_| Stop::Close("resync: community credential changed"))?; + let guard = state + .db + .community_artifact_read_guard(conn.tenant.community(), &interest.principal) + .await + .map_err(|_| Stop::Close("resync: community access changed"))?; + if !community_credential_current(state, conn, &interest.principal) + || !community_policy_current(state, conn, guard.requires_nip_fi()) + { + return Err(Stop::Close("resync: community authentication changed")); + } + Ok(Some(QueueGuard { + _database: guard, + _effect: effect, + })) +} +fn community_policy_current(state: &AppState, conn: &ConnectionState, required: bool) -> bool { + let mode = crate::nip_fi_policy::effective(state.config.nip_fi.mode, required); + !mode.denies_unconditionally() && (!mode.enforces() || conn.nip_fi_assertion.is_some()) +} +/// Credentials are checked independently of database admission. The common +/// node-wide backstop also uses this for idle syncs after a missed disconnect. +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()) + }) + }) +} +enum Snapshot { + Channel(buzz_db::ArtifactSnapshot), + Community(buzz_db::community_artifact::CommunityArtifactSnapshot), +} +impl Snapshot { + async fn next_page( + &mut self, + tags: &[(String, Vec)], + page: i64, + ) -> buzz_db::Result> { + match self { + Self::Channel(s) => s.next_page(tags, page).await, + Self::Community(s) => s.next_page(tags, page).await, + } + } + async fn finish(self) -> buzz_db::Result<()> { + match self { + Self::Channel(s) => s.finish().await, + Self::Community(s) => s.finish().await, + } + } } /// Rules 3–5 after `EOSE`: read each changed head, one read at a time, and @@ -750,11 +1036,18 @@ async fn run_live( if handle.cancel.is_cancelled() { return; } - let head = match state - .db - .artifact_head(conn.tenant.community(), reader, d, &filter.channels) - .await - { + 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 { Ok(head) => head.filter(|(head, _)| { bound.is_none_or(|allowed| { head.channel_id.is_some_and(|id| allowed.contains(&id)) @@ -785,7 +1078,16 @@ 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), + Some(state), + ) + .await + { Ok(()) => {} Err(Stop::Retired) => return, // One lost frame breaks the copy; the slow-client grace limit @@ -826,6 +1128,12 @@ 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; + } + + pub(crate) async fn revalidate(state: &crate::state::AppState) { + super::community_access::revalidate(state).await; } } @@ -994,17 +1302,19 @@ 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, 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, 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, None) + .await + .is_ok()); assert!(rx.try_recv().is_ok()); } @@ -1020,7 +1330,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, 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. @@ -1048,7 +1358,7 @@ mod tests { .try_send(WsMessage::Text("fill".into())) .unwrap(); } - let mut waiting = std::pin::pin!(send_eose("s", 1, &handle, &conn)); + let mut waiting = std::pin::pin!(send_eose("s", 1, &handle, &conn, None)); assert!(futures_util::poll!(&mut waiting).is_pending()); // The held list overflows while EOSE waits. for _ in 0..=MAX_SYNC_EVENTS { @@ -1065,7 +1375,7 @@ mod tests { // Without a pending resync, EOSE is queued. let clean = SyncHandle::new(); - assert!(send_eose("s", 1, &clean, &conn).await.is_ok()); + assert!(send_eose("s", 1, &clean, &conn, None).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/community_access.rs b/crates/buzz-relay/src/handlers/artifact_sync/community_access.rs new file mode 100644 index 00000000000..e9c7b8db8fb --- /dev/null +++ b/crates/buzz-relay/src/handlers/artifact_sync/community_access.rs @@ -0,0 +1,74 @@ +//! One jittered node-wide backstop for lost admission invalidations. Queries +//! batch distinct active principals, not subscriptions. Content delivery never +//! uses the result as a cache: it authorizes again through its queue guard. +use super::*; + +pub(super) async fn revalidate(state: &AppState) { + type Readers = HashMap< + (Vec, Option>, bool, bool), + (CommunityArtifactPrincipal, Vec>), + >; + let mut tenants: HashMap = HashMap::new(); + for entry in state.artifact_syncs.syncs.iter() { + let Some(interest) = &entry.community else { + continue; + }; + if !interest + .connection + .upgrade() + .is_some_and(|conn| community_credential_current(state, &conn, &interest.principal)) + { + entry.resync("resync: community credential changed"); + continue; + } + let (_, handles) = tenants + .entry(interest.tenant) + .or_default() + .entry(( + interest.principal.pubkey.clone(), + interest.principal.verified_owner.clone(), + interest.principal.require_membership, + interest.principal.owner_admission, + )) + .or_insert_with(|| (interest.principal.clone(), vec![])); + handles.push(Arc::clone(entry.value())); + } + for (community, readers) in tenants { + let readers: Vec<_> = readers.into_values().collect(); + for batch in readers.chunks(256) { + let principals: Vec<_> = batch.iter().map(|(p, _)| p.clone()).collect(); + let allowed = state + .db + .community_artifact_admission_batch(community, &principals) + .await; + for (index, (_, handles)) in batch.iter().enumerate() { + let current = allowed.as_ref().ok().and_then(|v| v.get(index)); + for handle in handles { + let permitted = current.is_some_and(|(required, admitted)| { + *admitted + && handle + .community + .as_ref() + .and_then(|i| i.connection.upgrade()) + .is_some_and(|conn| { + community_policy_current(state, &conn, *required) + }) + }); + if !permitted { + handle.resync("resync: community access changed"); + } + } + } + } + } +} + +/// The process has one watcher, with 45–75 s jitter. Immediate invalidations +/// normally close syncs; this bounds a lost cross-pod revocation while idle. +pub async fn watch(state: Arc) { + loop { + let delay = 45 + rand::random::() % 31; + tokio::time::sleep(Duration::from_secs(delay)).await; + revalidate(&state).await; + } +} 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..e7d082f8cd9 100644 --- a/crates/buzz-relay/src/handlers/artifact_sync_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/artifact_sync_postgres_tests.rs @@ -691,3 +691,5 @@ 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 new file mode 100644 index 00000000000..e41d5359f98 --- /dev/null +++ b/crates/buzz-relay/src/handlers/artifact_sync_postgres_tests/community_postgres_tests.rs @@ -0,0 +1,681 @@ +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(); +} + +/// Counterfactual: removing current_guard from send_reserved emits an EVENT +/// and EOSE after the member removal committed while output was reserved. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn revoked_initial_snapshot_never_emits_payload_or_eose_after_output_wait() { + for change in 0..6 { + let mut f = community_fixture().await; + if change >= 2 { + 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 { + 0 => remove(&f, &keys).await, + 1 => { + sqlx::query("UPDATE communities SET archived_at=clock_timestamp() WHERE id=$1") + .bind(f.tenant.community().as_uuid()) + .execute(f.state.db.pool()) + .await + .unwrap(); + } + 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(); + } + 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; + } +} + +/// A fresh head read is insufficient: current admission must be rechecked +/// after that read and before the live frame is queued. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn revoked_live_head_never_emits_after_committed_removal() { + let f = community_fixture().await; + let signals = artifact_sync::spawn_signals(Arc::clone(&f.state)); + let keys = Keys::generate(); + member(&f, &keys, "member").await; + let first = revision(&f, &keys, Uuid::new_v4(), None).await; + let d = first.tags.identifier().unwrap().parse().unwrap(); + let (conn, mut rx) = connect(&f, &keys); + 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::LIVE_SEND_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(), + ), + ), + ); + assert_eq!(initial_set(&mut rx).await, vec![first.id.to_hex()]); + revision(&f, &keys, d, Some(&first)).await; + tokio::time::timeout(Duration::from_secs(10), pause.reached.notified()) + .await + .unwrap(); + remove(&f, &keys).await; + pause.resume.notify_one(); + assert_eq!(frame(&mut rx).await[0], "CLOSED"); + ended(task).await; + no_frame(&mut rx).await; + 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_redact_and_invalidate_idle_syncs_with_lost_notification_backstop() { + 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 + ); + } + let at = start_sync(&f, &a, filter()); + let bt = start_sync(&remote, &b, filter()); + assert!(initial_set(&mut arx).await.is_empty()); + assert!(initial_set(&mut brx).await.is_empty()); + remove(&f, &reader).await; // Intentionally omit invalidation: exercise durable backstop. + artifact_sync::test_seam::revalidate(&f.state).await; + artifact_sync::test_seam::revalidate(&remote.state).await; + assert_eq!(frame(&mut arx).await[0], "CLOSED"); + assert_eq!(frame(&mut brx).await[0], "CLOSED"); + ended(at).await; + ended(bt).await; + local_fanout.abort(); + remote_fanout.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" + ); +} + +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn idle_sync_credential_revocation_uses_node_wide_backstop() { + let f = community_fixture().await; + let keys = Keys::generate(); + member(&f, &keys, "member").await; + let (conn, mut rx) = connect(&f, &keys); + let task = start_sync(&f, &conn, filter()); + assert!(initial_set(&mut rx).await.is_empty()); + if let AuthState::Authenticated(ctx) = &mut *conn.auth_state.lock().unwrap() { + ctx.scopes.clear(); + } + artifact_sync::test_seam::revalidate(&f.state).await; + let response = frame(&mut rx).await; + assert_eq!(response[0], "CLOSED"); + assert!(response[2].as_str().unwrap().starts_with("resync:")); + ended(task).await; +} + +/// 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 idle admission must not be merged with 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 + }; + remove(&f, &agent).await; // Deliberately drop both local and cross-pod disconnects. + artifact_sync::test_seam::revalidate(&f.state).await; + 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 { + no_frame(&mut rx).await; + 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(); + artifact_sync::test_seam::revalidate(&f.state).await; + 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 395aacfe4da..42b38b1d614 100644 --- a/crates/buzz-relay/src/handlers/close.rs +++ b/crates/buzz-relay/src/handlers/close.rs @@ -259,6 +259,12 @@ 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 new file mode 100644 index 00000000000..81dee7f43a2 --- /dev/null +++ b/crates/buzz-relay/src/handlers/community_artifact.rs @@ -0,0 +1,338 @@ +//! 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}; +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, + } +} +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) > 900 { + return Err(invalid("event timestamp too far from server time")); + } + if event.content.len() > 256 * 1024 { + 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)?; + outcome( + state, + tenant, + state + .db + .accept_community_artifact(community, &principal, event, &env) + .await + .map_err(storage_error)?, + ) + .await?; + } else if let Some(command) = command { + 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() > 256 * 1024 { + return Err(invalid("event content too large")); + } + let now = chrono::Utc::now().timestamp(); + if event.created_at.as_secs().abs_diff(now as u64) > 900 { + 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(), + } +} +async fn outcome( + state: &Arc, + tenant: &TenantContext, + outcome: buzz_db::artifact::ArtifactOutcome, +) -> Result<(), IngestError> { + use buzz_db::artifact::ArtifactOutcome; + match outcome { + ArtifactOutcome::Accepted(events) => { + for stored in events { + let env = artifact::validate(&stored.event).map_err(invalid)?; + signal( + state, + tenant, + buzz_pubsub::artifact_signal::ArtifactSignal { + d: env.id, + artifact_type: env.artifact_type, + cause: buzz_pubsub::artifact_signal::ArtifactChange::Changed, + }, + ) + .await; + } + } + ArtifactOutcome::Duplicate => {} + ArtifactOutcome::Conflict(reason) => { + return Err(IngestError::CanvasConflict(format!("conflict: {reason}"))) + } + ArtifactOutcome::Rejected(reason) => return Err(invalid(reason)), + } + Ok(()) +} +/// 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 781b3541c01..407adbb3313 100644 --- a/crates/buzz-relay/src/handlers/event.rs +++ b/crates/buzz-relay/src/handlers/event.rs @@ -150,6 +150,21 @@ 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(), @@ -313,6 +328,17 @@ 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 @@ -415,7 +441,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 => None, + buzz_pubsub::EventTopic::Global | buzz_pubsub::EventTopic::CommunityArtifact => None, }; StoredEvent::new(channel_event.event, channel_id) } @@ -714,7 +740,7 @@ pub async fn handle_event(event: Event, conn: Arc, state: Arc ( conn.conn_id, @@ -722,6 +748,7 @@ pub async fn handle_event(event: Event, conn: Arc, state: Arc { reject("auth"); @@ -933,7 +960,11 @@ 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. @@ -325,10 +335,56 @@ 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(), } } @@ -341,6 +397,7 @@ impl IngestAuth { pub fn scopes(&self) -> &[Scope] { match self { Self::Nip42 { scopes, .. } | Self::Http { scopes, .. } => scopes, + Self::Delegated { auth, .. } => auth.scopes(), } } @@ -349,6 +406,7 @@ impl IngestAuth { match self { Self::Nip42 { conn_id, .. } => Some(*conn_id), Self::Http { .. } => None, + Self::Delegated { auth, .. } => auth.conn_id(), } } @@ -361,13 +419,17 @@ 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 { - matches!(self, Self::Http { .. }) + match self { + Self::Delegated { auth, .. } => auth.is_http(), + _ => matches!(self, Self::Http { .. }), + } } } @@ -652,7 +714,7 @@ fn required_scope_for_kind(kind: u32, event: &Event) -> Result + || k == RELAY_ADMIN_SET_WORKSPACE_PROFILE || k == RELAY_ADMIN_SET_ARTIFACT_TYPE_POLICY => { Ok(Scope::AdminUsers) } @@ -865,6 +927,7 @@ 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 @@ -2548,7 +2611,7 @@ struct ChannelCreateRequest { members: Vec>, } -async fn validate_event_imeta( +pub(super) async fn validate_event_imeta( tenant: &TenantContext, state: &AppState, event: &Event, @@ -2640,6 +2703,17 @@ 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 diff --git a/crates/buzz-relay/src/handlers/mod.rs b/crates/buzz-relay/src/handlers/mod.rs index 19d9942e068..0abe40a6fd7 100644 --- a/crates/buzz-relay/src/handlers/mod.rs +++ b/crates/buzz-relay/src/handlers/mod.rs @@ -14,6 +14,8 @@ 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 afa25fd20f2..df41c9ac9ce 100644 --- a/crates/buzz-relay/src/handlers/side_effects.rs +++ b/crates/buzz-relay/src/handlers/side_effects.rs @@ -521,7 +521,12 @@ pub async fn validate_standard_deletion_event( return Err(anyhow::anyhow!("invalid a-tag format")); } if let Ok(target_kind) = parts[0].parse() { - if target_kind == KIND_VERIFIED_PROFILE { + if matches!( + target_kind, + KIND_VERIFIED_PROFILE + | buzz_core::kind::KIND_ARTIFACT + | buzz_core::kind::KIND_ARTIFACT_REMOVAL + ) { 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 3d233bc25c9..e22dd0788bf 100644 --- a/crates/buzz-relay/src/main.rs +++ b/crates/buzz-relay/src/main.rs @@ -1284,10 +1284,15 @@ 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, ))); + tokio::spawn(buzz_relay::handlers::artifact_sync::watch_community_access( + Arc::clone(&state), + )); // Multi-node fan-out: deliver events other relay instances published to // Redis to local WS subscribers (see `handlers::multinode_fanout`). diff --git a/crates/buzz-relay/src/nip11.rs b/crates/buzz-relay/src/nip11.rs index e58ec300961..b3bed55df2d 100644 --- a/crates/buzz-relay/src/nip11.rs +++ b/crates/buzz-relay/src/nip11.rs @@ -478,6 +478,14 @@ 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 58c1a188a91..92f01e8faf2 100644 --- a/crates/buzz-relay/src/protocol.rs +++ b/crates/buzz-relay/src/protocol.rs @@ -315,6 +315,8 @@ 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 361cf6d3715..aa1e016b942 100644 --- a/crates/buzz-relay/src/state.rs +++ b/crates/buzz-relay/src/state.rs @@ -1438,6 +1438,8 @@ 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. @@ -1811,6 +1813,7 @@ 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(), @@ -2249,6 +2252,7 @@ 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); } diff --git a/crates/buzz-relay/src/subscription.rs b/crates/buzz-relay/src/subscription.rs index e72608ec3fc..44d54bde19a 100644 --- a/crates/buzz-relay/src/subscription.rs +++ b/crates/buzz-relay/src/subscription.rs @@ -28,6 +28,7 @@ pub type SubId = String; #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct SubscriptionScope { global: bool, + community_artifact: bool, channels: Vec, } @@ -36,10 +37,24 @@ 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(); @@ -77,7 +92,7 @@ impl SubscriptionScope { } fn is_empty(&self) -> bool { - !self.global && self.channels.is_empty() + !self.global && !self.community_artifact && self.channels.is_empty() } /// The union of `scopes`: every topic any of them retains, once. @@ -85,6 +100,7 @@ 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 170d600ecc3..a97c3bd0455 100644 --- a/crates/buzz-search/src/query.rs +++ b/crates/buzz-search/src/query.rs @@ -329,8 +329,9 @@ pub async fn search(pool: &PgPool, query: &SearchQuery) -> Result 45010 OR (events.channel_id IS NOT NULL AND NOT events.tags @> '[[\"community\"]]'::jsonb))"); // 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 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 ah.scope='channel' 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 1cc084b2376..0e762f05559 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 = Uuid::new_v4(); + let (artifact, home) = (Uuid::new_v4(), Uuid::new_v4()); insert_event( &pool, community, @@ -1860,7 +1860,7 @@ async fn artifact_search_uses_only_live_current_head() { pk, 45010, "artifactneedle old", - None, + Some(home), 1700000000, ) .await; @@ -1871,12 +1871,12 @@ async fn artifact_search_uses_only_live_current_head() { pk, 45010, "artifactneedle current", - None, + Some(home), 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(Uuid::new_v4()).execute(&pool).await.unwrap(); + .bind(community.as_uuid()).bind(artifact).bind(head.as_slice()).bind(home).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 new file mode 100644 index 00000000000..80d69349c86 --- /dev/null +++ b/docs/community-artifact-rollout.md @@ -0,0 +1,107 @@ +# 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 + +Apply migration 0097, or converge the matching desired-state files. It adds +constant-default scope columns, nullable channel IDs, community revision JSON, +redaction state and a bounded policy map on `communities`. It retains the old +`(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. It is safe to rerun and writes +no payload data. Schema management must preserve this operator-selected key; +do not reconverge the expand-only desired-state primary key after contract. +A future contract release should update the declarative primary key after its +minimum compatible release has been established. + +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. +The idle backstop groups the complete principal context, including fallback +permission, so one session cannot admit another session of the same key. + +| 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 | Read current heads in one 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; acquire a fresh writer-backed admission guard outside the snapshot plus the existing FI effect permit. Recheck credential deadline, deny map and current community FI policy, then generation and pending invalidation, before enqueue. Shared community/member locks remain held through that point. | +| Live | A bounded typed Redis signal carries only identity, immutable type and change cause. Reload the authorized current head; never forward a published payload. Current-head redaction resyncs that type; historical redaction does not retire its successor. | +| Invalidation | Existing principal/owner disconnect fan-out handles revocation. A jittered 45–75 second node-wide batched DB backstop catches lost idle notifications. Every enqueue remains independently fenced. Unrelated restriction changes do not restart all tenant syncs. 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 writer capacity for enqueue rechecks even when every snapshot is paused +on output. Snapshot and fresh-guard acquisition each have a 2 second deadline; +statements and lock waits are capped at 2 seconds. 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 ddf13659f52..9d9cc4a50d9 100644 --- a/docs/nips/NIP-AR.md +++ b/docs/nips/NIP-AR.md @@ -249,7 +249,7 @@ A relay advertising `artifacts.community_scope.version = 1` accepts a second for "community_scope": {"version": 1, "community_id": "", "max_policies": 256} ``` -`max_policies` is the bound on stored type policies; the value shown is an example. +`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. @@ -278,9 +278,9 @@ The policy is tenant-scoped and keyed by the exact canonical artifact `type`. Mi 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. +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. Take the same policy lock before 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. A ban still refuses the replay. Check current community admission and the signed community before consulting receipts. +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. Take the same policy lock before 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 @@ -298,7 +298,7 @@ Use the same snapshot, buffer bounds, `EOSE` and head sequencing as channel sync 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. 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. +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. 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..ab3eb519516 100644 --- a/schema/tables/public/artifact_heads.sql +++ b/schema/tables/public/artifact_heads.sql @@ -2,8 +2,9 @@ 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, @@ -17,3 +18,8 @@ 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 UNIQUE INDEX artifact_heads_scoped_identity ON artifact_heads (community_id, scope, artifact_id); + +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) ); diff --git a/scripts/maintenance/community-artifact-contract.sql b/scripts/maintenance/community-artifact-contract.sql new file mode 100644 index 00000000000..8b8f0e90e12 --- /dev/null +++ b/scripts/maintenance/community-artifact-contract.sql @@ -0,0 +1,43 @@ +-- 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;