mirror of
https://github.com/block/buzz.git
synced 2026-11-24 10:12:19 +00:00
14e5ea7cc4ebd015ef3fe3371c1efb9aed4d3bef
1025 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
5268caa866 |
feat(push-gateway): mint FCM tokens through AWS workload identity federation (#9692)
## Summary Block's GCP projects forbid service account keys, so the push gateway can now get its FCM access token by federating its AWS identity (Google workload identity federation), with no key file. - `BUZZ_PUSH_FCM_SERVICE_ACCOUNT_PATH` is renamed `BUZZ_PUSH_FCM_CREDENTIALS_PATH` (no deployment sets it yet). The file is dispatched on its JSON `type`: `service_account` keeps today's JWT flow; `external_account` is Google's standard AWS credential configuration, the file Block's `identity-federation-aws` Terraform module generates. - Only the minting step changed. `TokenSource` caching, refresh, backoff and the Rejected/Unavailable split are as they were. - A federated mint: AWS credentials (EKS Pod Identity, IRSA or static env keys; no EC2 metadata), a SigV4-signed STS `GetCallerIdentity` subject token, Google STS, then `generateAccessToken` for the FCM scope. One 15 s deadline covers the whole chain. - Faults: network errors, 5xx and 429 on any hop are Unavailable; other 4xx are Rejected. - Startup checks the file's shape and the AWS environment but calls neither AWS nor Google, so an outage can't stop the gateway from serving iOS. The first mint's result is logged once. - Helm: `android.fcmServiceAccount` is renamed `android.fcmCredentials`, mounted as `credentials.json`. ## Validation - New tests drive `TokenSource` against fake AWS, Google STS and impersonation servers: the full chain, each hop's failure classification, a failed refresh keeping a valid cached token, the overall deadline, and config rejection cases. - SigV4 known-answer tests use AWS's documented example credentials, checked against an independent implementation. Checked live against the dev Firebase project from a local AWS identity: the federated mint succeeds and FCM accepts the resulting token. Not yet run from a gateway pod. --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> |
||
|
|
47c9a672d7 |
perf(push-gateway): evict the oldest signed-call window without scanning (#9799)
The push gateway's signed-call limiter keeps one counter per attested key, capped at 100,000 keys. Once the map was full, every call from a key not already in it scanned the whole map (once to drop expired windows, again to find the oldest), all while holding the limiter's lock. Under heavy load from many new keys, that serialized each signed call behind a 100,000-entry scan. The limiter now keeps a queue of window starts, oldest first, and evicts from its front. A key whose window restarts leaves a stale entry behind, which eviction skips; the queue is compacted once stale entries make up half of it, so a call stays O(1) amortized. Rate-limit behavior is unchanged, except that a full map now drops one oldest window per new key instead of every expired window at once. The map and the queue share one copy of each key; the queue can reach about twice the map's entries before compaction, so memory stays bounded. Follow-up from #9562. ### Validation | 1,000 new keys on a full map (release build) | Time | | --- | --- | | Before | 277 ms (about 0.28 ms per call, under the lock) | | After | 0.11 ms | - [`a_full_map_drops_the_key_with_the_oldest_window`](https://github.com/block/buzz/blob/push-gateway-limiter-eviction/crates/buzz-push-gateway/src/signed_call_limiter.rs) checks that eviction picks the oldest window. - [`eviction_skips_a_restarted_window`](https://github.com/block/buzz/blob/push-gateway-limiter-eviction/crates/buzz-push-gateway/src/signed_call_limiter.rs) checks that eviction skips a stale entry and keeps a key whose window just restarted. - [`restarted_windows_do_not_grow_the_queue`](https://github.com/block/buzz/blob/push-gateway-limiter-eviction/crates/buzz-push-gateway/src/signed_call_limiter.rs) checks that compaction bounds the queue when one key keeps restarting its window. --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> |
||
|
|
786726907c |
test(relay): cover member-cache invalidation routes and refill orders (#9748)
## Summary Add 54 cases that verify a relay cache refill cannot restore stale channel membership after invalidation. The cases cover stale grants and denials, reader and community isolation, and three orders in which reads can finish. The publish-wrapper cases exercise the local cache drop. The receiving handlers are tested separately. Both unit-test runners select the new cases. ### Related issue Test coverage for #9735 and #9742. ### Testing The read-cache lane passed all 26 tests on the reviewed tree. Both runners selected all three new tests. The draft will remain open while repository CI and human confirmation are pending. For manual verification, run `cargo test -p buzz-relay --lib state::tests::member_channel_invalidation_tests:: -- --nocapture` and expect three passes. Generated with Codex Signed-off-by: Brad Seiler <seiler@squareup.com> |
||
|
|
8d4b30176b | feat(cli): add many channel members per kind:9000 event (#9738) | ||
|
|
7e94503fe9 |
Stop using the unused delivery_log and subscriptions tables (#9746)
## Summary `delivery_log` and `subscriptions` came with the initial schema for a delivery feature that was never built. No code has ever written to them. This PR removes every reader, writer, partition-manager entry and deletion selection, so a follow-up contract migration can drop both tables (`docs/database.md` Rule 5: drop only after the release that stops using a table is fully deployed). - **Partition manager:** manages `events` only. It no longer creates or audits `delivery_log` partitions. - **User deletion:** the content, account and profile handlers no longer select, delete or recheck rows in either table. - **Community deletion:** both tables move from `EXPECTED_SCOPED_TABLES`/`PURGE_SCOPED_TABLES` to a new `RETIRING_SCOPED_TABLES` list. The catalog accepts each one present or absent. The purge deletes its rows only while it exists. `validate_approved_schema` accepts a frozen retiring table that has since been dropped, and no other missing table. Without this, every community deletion would fail its exact catalog check once the tables are gone. - **Docs:** a short "Retiring a tenant-owned table" section in `docs/database.md`, plus partition-monitoring and cleanup docs. The tables, their schema files, `.pgschemaignore` entries and the partition primary-key lint exception stay until the drop migration. ### Rollout 1. Deploy this release to every relay, deletion executor and operator CLI. Older binaries fail community deletion's exact catalog check after the drop. 2. Then ship the drop migration and remove the schema entries. Operators with external tooling that expects `delivery_log` to exist must update it first. The partition audit stops emitting `buzz_partition_audit_*` series with `table="delivery_log"`. Alerts keyed on that label will go quiet. ### What got simpler Two tables' worth of code paths are gone: partition management, the audit, and five deletion handlers stop special-casing them. The follow-up removes the tables and the `RETIRING_SCOPED_TABLES` entries. ### Testing On a remote workstation at `3675ff17`: `cargo fmt --check`, `clippy -D warnings` for buzz-db, buzz-deletion and buzz-relay (all targets), unit tests for buzz-db (lib and tests), buzz-deletion and buzz-relay bins, and `scripts/postgres-test-run.sh` for buzz-db partition/deletion/migration tests (294 passed) and all buzz-deletion Postgres tests (44 passed). The new tests cover: retiring tables purged and verified while present; a request inventoried before a real `DROP TABLE` still purges and verifies; `validate_approved_schema` tolerates only retiring tables vanishing. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
69ea27343c |
Fix media deletion’s community ownership and share agent discovery (#9670)
## Summary Deleting a human must preserve an agent's uploads in communities where someone else owns that agent or its profile is missing. Media cleanup now carries community/key pairs through database and storage discovery, shared-file decisions, and uploader-row deletion. Media, content, account and profile cleanup share one direct-agent discovery utility. Each caller retains its previous limits and transaction behavior. Media discovers ownership once per invocation, including retries, and uses a hash set for storage matching. The report shape stays unchanged. The operator guide explains that community/agent pairs have no separate cap and sit outside the inventory budget. The discovery helper documents that global, identity-grouped discovery requires `lock: false` because PostgreSQL cannot combine `GROUP BY` with `FOR SHARE`. Run a read-only preview first, then keep writers stopped throughout deletion. Reverting the binary restores the old cross-community selection bug; it cannot restore deleted objects. ### Related issue Follow-up to the merged media handler in #9365 and the content/account/profile handlers in #9363, #9364 and #9580. No duplicate of this ownership correction was identified. ### Testing Exercised the rebuilt `buzz-admin user-deletions media-batches --pubkey <fixture-human> --read-only`, then `--delete`, against isolated PostgreSQL and versioned MinIO. Preview changed neither rows nor storage. Exclusive versions and in-scope uploader rows were deleted; shared originals, thumbnails and historical versions survived. All four handler commands agreed before and after a between-invocation ownership change. Failure followed by retry used fresh ownership, and repeat deletion removed zero versions. Compared the production candidate SQL with the pre-PR query on about 50,000 local upload/audit rows. With 9,999 agents, execution took 120–185 ms per 500-row page versus 38–83 ms before community matching. Three runs per query; this excludes planning, Rust preparation and storage operations. The added per-version ownership queries are removed entirely. Full database/deletion/admin package runs passed (339 tests). The PostgreSQL database/deletion run passed 904 tests; after strengthening the retry fixture, the full deletion PostgreSQL package passed all 45 tests. The retry case retains ownership in another community, and media tests assert exactly one ownership lookup per invocation. Local `just test` completed with one failure in the unchanged relay logging test `composition_log_does_not_leak_issuer_url` (expected warning not captured); all other test groups passed. Two pre-push attempts failed in unchanged ACP tests: first a launch timeout, then credential tests using Git 2.40 where 2.46+ is required. All four credential integration tests passed with Git 2.54; the full pre-push retry was stopped at the author’s request to skip local checks and push. Local `just ci` was also stopped before completion. Neither interrupted run is a full pass; local hooks were skipped for publication. The follow-up for the optional review comments changes documentation only. Its statements were checked against the query and all five production callers; `git diff --check` passed. Runtime suites were not repeated for this follow-up. Human local acceptance remains pending. Generated with Codex --------- Signed-off-by: Ravneet Arora <rarora@squareup.com> Signed-off-by: dessert <7d616e7e143e5d408159614dccff1371350a1c1bd36c8de838a45ece5aca0aca@buzz.block.builderlab.xyz> Co-authored-by: dessert <7d616e7e143e5d408159614dccff1371350a1c1bd36c8de838a45ece5aca0aca@buzz.block.builderlab.xyz> |
||
|
|
729cb10b78 | buzz-db: drop the remaining relay foreign keys (#9740) | ||
|
|
890824f072 |
feat(read-state): sync mark read, channel mark unread and thread follows (#9501)
Reading, mark read, whole-channel mark unread and thread follow choices now sync across a person's installations. This PR specifies the rules in NIP-RS and implements them in the mobile app. ## Spec (`docs/nips/NIP-RS.md`) - Defines *catch-up* and *displayed*. - A catch-up advances the channel's own frontier (top-level messages) or `thread:<root>`. `activity:` and `thread-activity:` become read-only legacy keys. - Explicit mark read is synchronized state. A first explicit read of a message with no override group writes only its `msg:` frontier. Display, dwell, scroll, catch-up and mention visibility create no `msg:` entries. - Only whole-channel override groups are published, merged and cleared with the counter. Readers ignore peer `msg:` and `thread:` groups. - Single-message and thread mark unread stay on the device. They end once the merged frontier covering them passes their baseline, from any installation, or on display, catch-up or explicit read. The section also states clearing scope, the accepted concurrency limitation and capacity. - When the merged override union no longer fits the primary, the client rewrites the primary compactly from the groups its last published primary carried, each canonical against current frontiers. It never omits merged groups or tombstone floors that primary carried, and override actions fail visibly. - Adds Buzz Thread Follow Choices: `thread-follows:<32hex>` coordinates, validation, three-state verdict, last-writer merge with ties going to unfollow, publication and recovery, legacy import at `at = 0`, and capacity. ## Mobile - Catch-up writes the main frontier. A flat timeline reads up to the newest top-level message it reached. - Explicit mark read publishes. Passive `msg:` marks stay on the device. - Whole-channel mark unread publishes an override group and merges peer groups. An explicit read or catch-up clears it, even when no frontier moves. The action fails visibly at the uint32 limit or when the primary is full. A synced clear the primary can't carry is rolled back, and the channel view reports it once while the failure stands. - Device-local message and Inbox unread overrides record a baseline and clear when a covering frontier passes it, including one merged from a peer. - Thread follows move from local storage to the synced `thread-follows:` slots. They share the read-state `client_id`, journal, `created_at` sequence, snapshot and live subscription, and spill across up to 16 slots with stable placement. An unreadable coordinate marks follow state incomplete and blocks this installation's follow publication. - Follow and unfollow are refused on every cold start of the writer until its first complete recovery of its own state succeeds and every owned follow head is readable. Cached follows show at once. A refused tap changes nothing and shows "Follow choices are not ready. Connect and try again." Reads, catch-up and both kinds of mark unread are not gated. - A follow tap is accepted only once journaled. The accepted own head, pending edits and the exact in-flight packet are kept apart, so a retry or restore never drops or re-attributes an edit. - Pre-sync local follows are imported at `at = 0` after a complete merge, once their channel is known from a relay event. An imported key is settled, and its legacy copy retired, only when the journal write the import awaited covered it and that entry is still current. - An explicit unfollow suppresses ordinary replies at live and catch-up admission. A change in follow choices drops the unread replies already counted for an unfollowed thread. A newly followed thread re-runs catch-up only for its own channel. - A reading clear refused because the view hasn't completely loaded is retried after the next complete snapshot, including when publishing was shut off at the time. The view also counts as not completely loaded while the live subscription is reconnecting, so a read made while the phone is offline can't erase a newer unread mark set on another device. Offline, whole-channel mark unread is still refused, with a message. - Read-state events, including live ones, are verified with native libsecp256k1 before they are used. - A pending unread packet is counted as published only when no newer own head outranks it. When a newer head supersedes it, a successor is built above that head from the saved intent, and a late echo of a replaced packet doesn't overwrite what was published. - When the merged unread state overfills the primary and the compact fallback can't carry a pending mark, the packet stays pending and the "read state full" error shows. Other queued reads and follows in the same flush still publish. - When this installation's own unread record can't be decoded, only the unread step is held: that record isn't overwritten, its pending marks stay queued and the sync error shows. Other queued reads and follows in the same flush still publish. - The sync notice stays up after an unsupported refusal until a new session. Offline, it can't be tapped and says it will retry when back online. - Two-device fixtures against an in-memory relay cover channel round-trips and clears, stray message groups, the first explicit message read, the primary cap, follow propagation, same-second and backward-clock follow publication, legacy import, retry after a failed publish, unreadable coordinates and slot packing. Recovery fixtures cover the startup gate, journal failures during flush, interleaved legacy imports, and restore of an older journal. ## Relay - Conforming `thread-follows:<32 hex>` records get the NIP-RS treatment: a replaced record is purged, and a stale resend of an older one is refused. Records with a mismatched `t` tag keep ordinary replaceable-event behavior. ## Known gap - An unread packet held for capacity can age past the relay's timestamp window. The relay then refuses it, and the refusal path retires it without the capacity check, so the error clears and other installations don't get that mark. The mark stays on the device. Related: [block/buzz-app#3552](https://github.com/block/buzz-app/pull/3552) --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Signed-off-by: Will Pfleger <wpfleger@squareup.com> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow <tomb@block.xyz> |
||
|
|
cda68a9333 |
Fix shared stars and mutes in mobile and CLI (#9684)
## Summary Mobile, CLI, and legacy desktop write millisecond timestamps for new star and mute edits. They compare legacy seconds in the same unit and retain the original timestamps of untouched entries during rollout. Mobile and CLI cap saved records at 500 entries and repair oversized records on a write. CLI no-op adds and removes leave oversized records alone. They keep the current edits and evict by age, preferring clears when timestamps tie. The CLI accepts a full flag record within the short-form NIP-44 envelope. Mobile builds each write from the writer's retained snapshot plus a durable journal of local edits. The journal drains in batches of at most 500 edits. It retries transient failures and older writer snapshots with bounded backoff and retires a pending edit after verifying that the writer already holds it or holds a strictly newer one. Retried writes preserve the original entry timestamps. An exact timestamp tie with a conflicting writer value advances by one millisecond so older clients accept the edit. An unreadable record pauses writes until a valid snapshot or app resume. On mobile upgrade, a verified writer snapshot lets the app recover newer local star and mute edits from the old cache. The legacy cache has no edit journal. Below 500 writer entries, the app also recovers absent active flags. At 500 or above it only recovers absent active flags dated after the snapshot's creation second. Absent legacy clears and clears newer than the writer's recorded clear are kept locally. They enter the publish queue when an older or equal enable appears. If the enable disappears before preflight, the clear returns to the local cache. A newer enable, an equal or newer clear, or a fresh tap retires the saved clear. A cached enable is queued when it is newer than the writer entry or ties a writer clear. A strictly newer cached enable advances the timestamp even when both copies are enabled. Recovered enables and promoted clears keep their original stamps in the journal. When the relay entry is absent or uses seconds, the write keeps a recovered seconds stamp so a later edit from an older phone can win. An existing millisecond entry uses millisecond comparison and serialization for the recovered edit. ## Validation - Mobile regressions exercise a later seconds-stamped edit, two-device eviction, a pending clear at the cap across manager replacement, transient read recovery, a losing duplicate acknowledgement, and a second toggle during confirmation, including at the cap. - CLI regressions cover seconds-stamped entries, the 500-entry limit, recovery from oversized records, and clear retention, including a repeated remove that leaves active flags intact. - Runtime validation uses scripted relays. - All 702 CLI tests passed. - Pre-push gates passed, including the full Flutter suite and analysis, repository Rust tests, and desktop Tauri checks. - Legacy desktop tests cover mixed-unit merges and back-to-back toggles. Mobile upgrade regressions cover newer offline entries, eviction, reconnect, and malformed-head recovery. --------- Signed-off-by: Wes <wesb@block.xyz> Co-authored-by: Star Lord <b89298dbe87c6b3fd8a425b535d9d161f23c88d555a47925ae0b04dfe02b201e@buzz.block.builderlab.xyz> |
||
|
|
e581555bf8 |
perf(relay): serve named-only channel access from the access caches (#9735)
## What
REQ, COUNT, `POST /query` and `POST /count` now take a reader's
named-only channel access (system channels, and any type added later)
from the two access caches they already read. Before, any filter that
opted in to system channels, or named a channel outside the implicit
set, ran `get_readable_named_only_channels` on the writer, uncached, on
every request.
## Why
Clients send such a filter on every connect. buzz-app's system channel
discovery reads `{kinds:[39002], "#p":[me], "#t":["system"]}`. So a
fleet reconnect (rollout, relay restart, network blip) paid one extra
uncached writer read per client, on top of the cached access set. This
read showed up near the top of writer SQL during reconnect herds.
## How
- `get_member_channels_read_at` and `get_listed_open_channels_read_at`
(buzz-db) return every channel type, with their connection checkout
time, and split rows into the implicit set (legacy types) and the
named-only set, with the type. They are the same two queries as before,
without the type filter. `get_member_channel_ids` and
`get_listed_open_channel_ids` keep their results.
- With no names, the two named-only halves together are exactly what
`get_readable_named_only_channels` returns. A new Postgres test pins
that equality for a member and a non-member.
- `AppState::get_channel_access_cached` returns a `ChannelAccess` from
the member cache (per pubkey, 10 s, dropped on every membership write)
and the open cache (1 s, shared reads). It yields the named-only
channels on demand, so a request that uses only the implicit set does no
extra work. `get_accessible_channel_ids_cached` is now a wrapper around
it.
- Both caches' refills are fenced against invalidation by a small shared
`LoadFence` (new `load_fence.rs`), as `MembershipCache` does.
Overlapping misses for a key share one load token, so the first read to
finish publishes. Invalidation drops the token, and a read publishes
only while its token is current. Before, a read that began before a
removal (or an open-to-private change) could finish after it and cache
the old set. That race also affected private stream/forum channels.
- The member snapshot is dated from its read's connection checkout, like
the open set, and a hit older than `MEMBER_CHANNELS_MAX_AGE` (10 s)
reads again. Before, its 10 s started at insert, so a slow read
stretched the bound.
- `readable_named_only_channels_for_filters` uses the cached set when
every channel the request names outside the implicit set is in it. The
system opt-in needs exactly that set. When a request names any other
channel (an unlisted open channel, or one it can't read), it keeps the
uncached read, unchanged.
- A `"consistency": "strong"` `POST /query` takes its named-only access
from the database, so a client that just created a system channel finds
it even on a pod that has not yet seen the invalidation. REQ, COUNT and
`POST /count` keep the cache.
- The thread-window and workflow checks keep the uncached read.
## Staleness
Same as the implicit set's today. Every membership write
(`invalidate_membership`) drops the per-pubkey entry, whatever the
channel type, and the drop is sent to every pod. On the pod that ran the
removal, the next request sees it (the refill fence closes the race). A
missed cross-pod drop keeps a removed member's system channel for up to
10 s after the read began on that pod, as for a private channel. The
open half is used for 1 s.
## What got simpler
No new access cache and no new invalidation trigger. The named-only
access now comes from the same snapshot as the implicit set, so REQ no
longer mixes a cached implicit set with an uncached named-only set.
`get_member_channel_ids` and `get_listed_open_channel_ids` no longer
have their own SQL, and their unused `Db` wrappers are gone. The two
replacement reads keep the old span names (`get_member_channel_ids`,
`get_listed_open_channel_ids`).
## Tests
-
`handlers::system_channels::tests::cached_access_answers_named_only_needs_without_a_database_read`
(unit, unreachable DB): discovery and a cached `#h` name are answered
with no read, the token scope still narrows the result, and a name
outside the cached sets reads the database.
-
`store::unlisted_channels_postgres_tests::cached_channel_sets_match_the_uncached_named_only_read`
(Postgres): the cached halves equal the uncached read and the accessible
set.
-
`state::tests::a_member_read_that_straddles_an_invalidation_is_not_cached`
(unit): a read held open through a per-user or a community-wide
invalidation answers its own request but is not cached.
-
`state::tests::an_open_read_that_straddles_an_invalidation_is_not_cached`
(unit): an open-set read held open through the community's invalidation
answers its own request, and the next request reads again.
- `state::tests::a_member_snapshot_ages_from_its_read_not_its_insert`
(unit): a member snapshot already 10 s old when published is not served.
- `state::tests::overlapping_member_reads_cache_the_first_to_finish`
(unit): a second miss that starts while the first read is in flight does
not stop the first from being cached.
-
`handlers::system_channel_postgres_tests::a_strong_query_sees_a_just_created_system_channel_past_a_stale_cache`
(Postgres): a strong `/query` finds a just-created system channel past a
stale member entry.
-
`handlers::system_channel_postgres_tests::a_token_scope_narrows_system_channels_on_both_access_paths`
(Postgres): token-scoped WS REQ and COUNT, through the cache path and
the database path.
- Must-fail mutants: always take the database branch; keep only legacy
types in the member query; drop the token scope at the REQ call site;
publish without the fence check; drop the open-set token on
invalidation; ignore the member snapshot's checkout age.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Tom Brow <tomb@block.xyz>
|
||
|
|
d9c3f4e99e |
Remove personal workflow data and missed event copies (#9675)
## Summary User content cleanup left private hide-list snapshots, saved workflow inputs and notes, unused automation, and some delivery copies behind. This extends the existing per-community content handler to remove them with the same preview, ownership and retry checks. - Delete trusted-relay hidden-DM snapshots and author-signed historical file-metadata events (kind 1063). - Clear recorded event-trigger text/emoji, authenticated manual inputs, and the recorded approver's note while preserving the rest of each run or approval. - Delete unused workflow database definitions and their schedule claims together. Any run, approval or linked claim protects the definition. The entire group must fit the requested batch size, capped at 100 rows, or planning refuses before mutation. - Delete delivery logs under surviving subscriptions before erasing their source events; reject newly arrived dependent rows before committing. Check the whole event batch with hashed membership to avoid repeated work across unrelated delivery history. Run deletion offline with the relay, workflow engine and external writers stopped. Shared history, canvases, artifacts, Git data and device registrations remain outside these additions. Retained runs can subsequently read the cleared inputs; this does not cancel them or claim complete account erasure. Existing signed kind 30620 event cleanup is unchanged. This is an application-only change against existing tables. It adds no migrations, indexes, triggers, functions or foreign keys. Existing per-statement timeouts and community write admission remain in use. ### Related issue Related: #9353. Extends the content handler in #9363. Shared workflow ownership policy remains separate from these personal-field deletions. ### Testing Ran the rebuilt `buzz-admin user-deletions content-batches --community <fixture-community> --pubkey <fixture-user> --batch-size 100` against disposable PostgreSQL 17 fixtures with 100 events, 500,000 unrelated delivery logs, and 9,999 small communities. `--read-only` selected 100; `--delete` removed 100 in 0.39 seconds locally; a second `--delete` selected zero. All 500,000 unrelated same-community delivery rows survived. EXPLAIN used hashed membership under both custom and generic plans. Independent review also exercised stale statistics. Removing the planner safeguard made the regression fail at the executor's actual 3-second timeout. The late-copy test still refuses deletion and preserves the source until retry can include the new copy. Independent agent review completed with no remaining blockers. Earlier command validation on the original patch exercised all agreed additions: preview nine operations, delete nine, retry zero, with whole-row preservation checks for the other community, shared canvas, surviving subscriptions, workflow output/provenance, and other approvers' notes. The repository-wide `just ci` run passed static checks, then stopped on two timeouts in unchanged `buzz-agent` OAuth tests. Both cases passed a serial recheck. The subsequent normal push hooks passed, including the complete Rust unit lane and Tauri checks. Later app build/test recipes were not reached; the full local CI command is not claimed green. Human command verification is pending, so this PR remains draft. On disposable fixtures, run the same preview/delete/retry sequence and verify that only the planned rows/fields change. Generated with Codex --------- Signed-off-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz> Co-authored-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz> |
||
|
|
946d9c3467 |
fix(relay): rename target log field to target_pubkey (#9739)
Rename the relay's custom structured log field from `target` to `target_pubkey` at the affected call sites. `tracing` also writes its own `target` field (the module path) after callsite fields, and Datadog keeps the last value. That overwrites the pubkey; using `target_pubkey` preserves it without changing tracing's built-in `target` metadata used by `RUST_LOG` and Vector routing. Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Alia <d32955ad69077062930cc46cfe2df30ca9aaf6f8e76422681265e9e9af704d78@buzz.block.builderlab.xyz> |
||
|
|
379b501124 |
feat(push-gateway): declarative desired-state schema, one file per table (#8328)
## Summary Gives the push gateway a declarative desired-state schema in the same layout the relay uses since #8131: a `\i` manifest plus one file per table, the shape SchemaBot reads. - `crates/buzz-push-gateway/schema/schema.sql`: an ordered `\i` manifest and nothing else. - `crates/buzz-push-gateway/schema/tables/public/<table>.sql`: the end state of migrations `0001`–`0008` for all six gateway tables. That includes `0007`'s `installations.platform` column and `0008`'s dropped delegation → installation foreign key (#9610), so the delegation table declares no `REFERENCES`. Each file holds only its `CREATE TABLE` and plain `CREATE [UNIQUE] INDEX` statements. - `src/postgres.rs`: the six table names are now one `GATEWAY_TABLES` constant shared by readiness and the runtime-role GRANT, instead of two hand-copied lists. - `src/postgres/desired_schema_postgres_tests.rs` adds two tests: - `desired_state_schema_layout_is_complete_and_schemabot_shaped` (no infra needed). It checks that the manifest includes every file exactly once and holds only `\i` lines, that each table file creates exactly one table, and that indexes use a plain `CREATE INDEX` on that table. - `desired_state_schema_matches_migrations` (PostgreSQL lane). It builds one probe database from `schema.sql` through the real `bin/pgschema apply` and another through `GATEWAY_MIGRATOR`. It then requires the two `public` catalogs to match: table set, columns from `pg_attribute` (full type with typmod via `format_type`, default, nullability, identity, generation, collation), table options (persistence, RLS flags, `reloptions`), constraints (`pg_get_constraintdef`) and index shapes (`pg_get_indexdef` + `indoption`). Neither probe may hold functions, non-internal triggers, policies, views, sequences or user types, and the declared table set must equal `GATEWAY_TABLES`. It compares the whole `public` catalog, not a list of tables, so a future migration that changes `public` tables, columns, table options, constraints or indexes without a matching `schema/` change fails CI. It doesn't cover data-only migrations or objects outside `public` (other schemas, roles, database settings). Probe databases are created from `template0` and dropped even when an assertion, `pgschema` or setup fails; the original failure is re-raised unchanged. Connection details, including the password, come from the resolved `PgConnectOptions`, so percent-encoded credentials, `?password=` and Unix-socket URLs reach `pgschema` the way SQLx sees them. `pgschema` 1.7.4 builds an unquoted keyword DSN, so a password or socket path with whitespace, a quote, `=` or a backslash isn't supported (noted in the test). ## Not changed The gateway still migrates itself at startup: bootstrap guard, then SQLx migrations, then runtime-role grants. The guard and grants are operational steps, not desired-state DDL, so they stay in code. No `schemabot.yaml` is added: SchemaBot isn't configured for the relay or the gateway yet, so the yaml for both waits until that server-side setup exists. The manifest header notes that the relay's post-pgschema reconcile step (root `AGENTS.md` gotcha #7) doesn't apply, because the gateway schema has no seed DML or storage parameters. SchemaBot compatibility is not proven here. The parity test shows the files are equivalent under `pgschema`. Since #9610 the gateway schema has no foreign keys, so the earlier inline-FK caveat is gone. `docs/database.md` Rule 4 now lists the gateway `schema/` directory as a schema location. ## What got simpler To read the gateway's schema today you have to replay eight migrations: two CHECK rewrites, two dropped UNIQUE constraints, a dropped column, an added column and a dropped foreign key. After this PR it's one declarative file per table, in the same convention as the relay. There is no new runtime path and no new abstraction, and the duplicated table list in `postgres.rs` collapses to one constant. ## Testing At `c4336392` (rebased on main after #9610; mirrors gateway `0007`/`0008`; reads the `pgschema` password from a copy with a URL-safe host and username, so a `PGHOST` or default-search socket no longer panics and a `/role` username no longer drops the password): - `cargo fmt --all -- --check` and `cargo clippy -p buzz-push-gateway --all-targets -- -D warnings`: pass. - `cargo test -p buzz-push-gateway --lib desired_schema`: pass, including `resolved_password_reads_through_a_socket_host_and_slash_username`. Removing the username normalization makes that test fail. - `scripts/postgres-test-run.sh -p buzz-push-gateway --lib --tests`: 17/17 passed, including `desired_state_schema_matches_migrations`. At `df3ff104` (password from resolved connect options), same workstation: - fmt, clippy (`-D warnings`, with and without `personal-dev-app-attest`): pass. `cargo nextest run -p buzz-push-gateway`: 80/80, and 82/82 with the feature. `scripts/postgres-test-run.sh -p buzz-push-gateway --lib --tests`: 13/13. - `?password=`: with `PGPASSWORD` unset, `postgres://<role>:wrong@localhost/postgres?password=<encoded p@ss:w/rd#x>` passes the parity test, so `pgschema` gets the query-parameter password that SQLx uses. A wrong `?password=` is rejected (`28P01`). - The CHECK-bound falsification still fails with `constraint parity mismatch`. Every run leaves 0 probe databases. At `f937924a` (probe cleanup and connection-URL follow-up), on a Linux workstation against PostgreSQL 16 with the repo's pinned `bin/pgschema`: - `cargo fmt --all -- --check`, plus `cargo clippy -p buzz-push-gateway --all-targets -- -D warnings` with and without `--features personal-dev-app-attest`: pass. - `cargo nextest run -p buzz-push-gateway`: 60/60 passed, and 62/62 with `personal-dev-app-attest`. `scripts/postgres-test-run.sh -p buzz-push-gateway --lib --tests`: 12/12 passed. - Probe cleanup: with a CHECK bound changed (2048→4096), the previous test code fails and leaves both `push_gateway_{desired,migrated}_*` databases behind. The new code fails with the same `constraint parity mismatch` panic and leaves none. A table file that makes `pgschema apply` fail (`no_such_column`) also reports `pgschema apply failed: ... column "no_such_column" does not exist` and leaves none. - Connection URLs: the parity test passes as a role whose password is `p@ss:w/rd#%x`, given percent-encoded in the URL with `PGPASSWORD` unset. It also passes over `postgres://<user>@%2Fvar%2Frun%2Fpostgresql:5432/postgres` (Unix socket, peer auth). Earlier, at `ee2745cb78`: - `scripts/postgres-test-packages.sh` discovers `buzz-push-gateway`. The parity test lives under a `*_postgres_tests` module so the `postgres-ci` nextest filter selects it. - `cargo fmt --all -- --check` and `cargo clippy -p buzz-push-gateway --all-targets -- -D warnings` both pass. - `cargo nextest run -p buzz-push-gateway`: 60/60 passed, including the layout test. - `scripts/postgres-test-run.sh -p buzz-push-gateway`: 12/12 passed, including `desired_state_schema_matches_migrations`. - Falsification checks: - Dropping the partial predicate from `push_gateway_installations_active_token` makes the parity test fail with an index-shape mismatch. - Adding an unmirrored `0007` migration (`ADD COLUMN probe TEXT`) makes the parity test fail with a column mismatch. Mirroring the column in the table file makes it pass again. - Putting `CREATE TABLE` DDL in `schema.sql` makes the layout test fail. - A `0007` adding `probe VARCHAR(64)` mirrored as `VARCHAR(128)` fails with a column mismatch (typmod); mirroring it exactly passes. - An unmirrored `0007` `ALTER COLUMN expires_at TYPE TIMESTAMP` fails with a column mismatch. - An unmirrored `0007` `ENABLE ROW LEVEL SECURITY` fails with a table-option mismatch. - A `0007` creating a function and trigger fails the "only tables and indexes" check. Known gap: `sqlx::migrate!` doesn't notice a *new* migration file on an incremental build. The crate has no `build.rs` `rerun-if-changed`, and neither does any other crate in the workspace. For the `0007` check above I touched `src/postgres.rs` to force the macro to re-expand. Clean CI builds aren't affected. buzz-review-completed --------- Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
7e7ec731cd |
test(cli): keep the raw refusal exit test independent of BUZZ_* env (#9733)
## Summary
Follow-up to #9653. Its new test
`cli_exits_nonzero_when_the_relay_refuses_a_raw_publish` went through
`run_from_args`, which resolves credentials from the caller's
environment. With `BUZZ_AUTH_TAG` set (as it is for agents run by the
ACP harness), the test client's key doesn't match the auth tag and the
test exits 3 instead of 2.
The check moves to an integration test,
[`tests/raw_publish_exit.rs`](
|
||
|
|
bc3023a050 |
push-gateway: drop the delegation → installation foreign key (#9610)
## Summary Retire the last foreign key in the push gateway schema: `push_gateway_delegations.installation_id → push_gateway_installations(id)`. This follows `docs/database.md` Rule 2 and the relay FK retirement work (#9399, #9404). - **Gateway migration 0008** drops the constraint. - **Relay migration 0101** drops the relay's legacy copy (Rule 4: gateway schema changes go in both). `schema/tables/public/push_gateway_delegations.sql` loses the inline `REFERENCES`. ## Required stop Every gateway and rollback target must run #9627 (`44cdd9fe`) or later before this merges and deploys. #9627 makes the reaper lock expired installations before it deletes their delegations. Without the FK, an older reaper can leave an orphaned delegation. This is step 2 of the Rule 5 retirement sequence; #9627 is step 1. ## Why the app already enforces the reference | Path | Check | |---|---| | `upsert_delegation` (only delegation insert) | Locks the installation `FOR UPDATE` in the same transaction; rejects a missing or revoked one. | | `create_installation` (replaces expired installations) | Locks the matching installations `FOR UPDATE`, deletes their delegations, then the installations. | | `reap_expired` | Locks expired installations `FOR UPDATE`, deletes their delegations, then the installations (#9627). | | `authorize_delivery` | Reads the installation through the delegation; a missing installation is `Rejected`. | | `revoke_delegation` | Updates the delegation only; an orphan has no effect. | | `revoke_installation`, `rotate_endpoint`, `advance_assertion_counter` | Update the installation; they never delete it. | The relay never reads or writes the `push_gateway_*` tables (the gateway requires its own database), so dropping the relay copy changes no relay behavior. ## Tests The gateway tests run against the migrated schema, which no longer has the FK, so they prove the app check. - `migrated_schema_has_no_foreign_keys` (new): the gateway schema has no foreign keys after migrations. It fails if gateway migration 0008 is removed. - `delegation_for_missing_installation_is_rejected` and `reaper_deletes_delegation_committed_while_it_waits` (from #9627) now run without the FK. - `reaper_retains_revocation_tombstones_until_authority_expiry`: its hand-built schema drops the FK too. - Relay: `push_gateway_delegations` joins the constraint parity check in `admin_schema_parity_between_desired_state_and_migrations`, and the migration count test covers 0101. ## Validation Blox at `33f7df90` (before the rename to 0101; CI covers the rebased head): - `cargo fmt --check`, clippy (`buzz-push-gateway`, `buzz-db`, all targets), gateway unit tests, `buzz-db` migration unit tests: pass. - `scripts/postgres-test-run.sh -p buzz-push-gateway --lib --tests`: 16/16 pass. - `buzz-db` Postgres tests for migrations, parity, push, floor retirement and retained guards: 56/56 pass, including `admin_schema_parity_between_desired_state_and_migrations`. - Must-fail check: with gateway migration 0008 removed, `migrated_schema_has_no_foreign_keys` fails (1 foreign key vs 0). ## Coordination - On main after #8696, #9398 and #9710 (relay 0095–0100). #9627 shipped this PR's reaper fix and tests separately, so this PR is the schema drop only. - Renumbered to relay 0101 after #9710 took 0098–0100 (rename only; file contents unchanged). #9690 and #9621 also add a relay 0098; whichever merges second renumbers. - #8328 adds the gateway's declarative schema with the inline FK. Whichever PR merges second removes it there. ## What got simpler One fewer database object. Every gateway reference check now lives in one place: the gateway's own transactions. buzz-review-completed 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
5ccbb61190 |
feat(cli): add raw query and publish escape-hatch commands (#9653)
## Summary Agents using the CLI had no way to answer questions like "which channels is key X a member of" (kind 39002 with `#p`) without scanning channels one at a time, which runs into identity-adapter rate limits. This adds a small escape hatch that reuses the CLI's existing credentials (signing key, auth tag, federated identity assertion): - `buzz raw query <filter>`: send one filter object or an array of filters (or `-` for stdin) to the relay's `/query` endpoint and print the relay's JSON as-is (an event array, or an object for filters such as read-state snapshots). - `buzz raw publish`: build, sign and send an arbitrary event, either from `--kind`, repeatable `--tag` (JSON arrays, as in `social set-list`) and `--content`, or from a full `--event-json` template. Signing goes through `sign_event`, so the auth tag is attached as for every other command; a caller-supplied `auth` tag is refused. Ephemeral kinds (20000 to 29999) use the ephemeral publish path, except the NIP-43 leave request (28936), which goes over HTTP because the relay revokes the submitting socket on success. Gift wraps (1059) are refused, since they need NIP-59 signing with a throwaway key. Malformed input (bad JSON, a filter that isn't an object, a bad tag) exits 1 with the usual `user_error` JSON; the relay validates filter fields itself, and its rejection exits 2 as a relay error. A publish the relay refuses (`accepted:false`, over HTTP or the WebSocket) exits 2 with the event id and message. README and TESTING.md list the new commands and their limits (replaceable and addressable kinds replace the whole event; kind-scoped credentials can fail artifact revisions). ## Regressions None expected: this adds a new command group and does not change existing commands. `submit_event` now also gives the relay-admin kinds (9030 to 9033), identity archive and unarchive requests (9035, 9036) and the leave request (28936) the moderation retry policy (no blind resend after an ambiguous outcome). `agents archive` and `agents unarchive` send 9035 and 9036, so after a lost response they now report an unknown outcome instead of resending, which could re-archive over a later unarchive. ### Validation Tried against a live relay as a signed-in user: a kind 39002 `#p` query listed one key's channels, a two-filter array and an `ids` lookup returned the expected events, and `raw publish` sent a typing indicator, a reaction and a deletion of that reaction, all accepted. New tests in [`raw.rs`]( |
||
|
|
98e2b7cbbc |
feat(relay): push mentions to people outside a listed channel (#9623)
## Summary A message that `p`-tags someone in a listed channel they haven't joined now sends them a push. Before this, push woke only channel members. This is the relay part of "Let them know", a choice for mentioning people outside a public channel. The client changes are https://github.com/block/buzz-app/pull/3769, https://github.com/block/buzz-app/pull/3771 and https://github.com/block/buzz/pull/9629. - The matcher wakes a non-member only when a `p` tag names them and the channel is open, not unlisted, and a stream or forum. It reuses the channel directory's `LISTED_CHANNEL_SQL`. - Delivery checks again before sending. The channel must still be listed, the event must still mention them, and they must still be able to connect. A ban on them or their agent's owner blocks the push, and so does a missing membership or allowlist entry when the relay requires one. - Members, private and unlisted channels, DMs and system channels are unchanged. **Needs security review.** This decides who gets push wakes. A wake goes only to someone who could already read the event with `REQ`, and it carries no message content. Follow-up: a banned or removed channel member still gets wakes until their lease expires. That predates this PR, and the fix belongs in the ban and removal code. ### Related issue None found. ### Testing - Postgres tests run ingest through delivery against a fake gateway. They cover private, unlisted and system channels, a switch to private before delivery, bans, removal, a missing allowlist entry, and an agent relying on its owner's membership. I made 20 small changes that each broke one of these checks, and each one made a test fail. - On a local relay with a stand-in gateway, an outsider's mention push arrived, and nothing went out after a ban, a removal or a switch to private. With the new delivery check turned off, the banned and removed people got pushes. - Not tested: a real gateway and a phone. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Soheyl Vakili <soheyl@squareup.com> Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Tom Brow <tomb@block.xyz> |
||
|
|
9ea57cba2a |
fix(db): undo migration 0097 (#9710)
## What Migrations `0098`–`0100` undo migration `0097` (community artifact expand). The declared schema goes back to its shape before #9650. #9650 added `0097`. The revert, #9689, removed the feature but kept `0097` byte for byte, because databases that auto-migrated recorded its checksum. No code on `main` reads or writes what `0097` added. This PR removes it with forward migrations, as `docs/database.md` requires ("Never edit a merged migration. Fix forward."). `artifact_heads.channel_id` gets `NOT NULL` back in the three steps from *Adding `NOT NULL` to a populated table*: - `0098` checks that the artifact head key is `(community_id, artifact_id)`, then adds `CHECK (channel_id IS NOT NULL) NOT VALID`. - `0099` validates the check under `SHARE UPDATE EXCLUSIVE`, so channel artifact reads and writes continue. - `0100` sets `NOT NULL` from the validated check (no scan), drops the check, drops `artifact_heads_live_type`, `artifact_heads_scoped_identity` and `artifact_revisions_scoped_identity`, and drops `artifact_heads.scope`, `artifact_revisions.scope`, `artifact_revisions.community_event`, `artifact_revisions.redacted` and `communities.artifact_type_policies`. The primary keys don't change. `0097` never changed them. ## Review checklist (docs/database.md) - **Phase:** contract. It follows the expand in #9650 (`0097`) and the code revert in #9689. - **Required stop:** every relay pod, job and rollback target must run #9689 (`sha-a406191`) or later before `0100` runs. The chart's upgrade notes (`deploy/charts/buzz/README.md`) say this, along with how to roll back with auto-migration off. No tagged relay release contains #9650. Only rolling images from `eebf62b6` up to, but not including, `a4061916` are affected. Relays built from #9650 itself read `artifact_heads.scope` and write with `ON CONFLICT` on `artifact_heads_scoped_identity`. Releases before #9650 never read these objects. - **Fails closed:** `0098` refuses a database whose artifact head key is the scoped key from #9650's removed operator contract script or declared schema. That database needs the recovery in #9689's Compatibility section. `0099` fails if any head has a null `channel_id`. Both stop before any cleanup. - No trigger, function, procedure, rule or foreign key is added. No migration changes existing rows. - Every schema location in Rule 4 is updated: `migrations/` and `schema/tables/public/` (`artifact_heads.sql`, `artifact_revisions.sql`, `communities.sql`). No reconcile-script or gateway change applies. - **Currently deployed relay:** a relay from #9689 or later doesn't use these objects, and neither does a relay from before #9650. The populated-table test runs every migration over channel artifact data. - **Locks:** each migration sets `lock_timeout = '5s'` and `statement_timeout = '30s'`. No index is built. ## Tests - `admin_schema_parity_between_desired_state_and_migrations` compares `artifact_heads`, `artifact_revisions` and `communities` across the desired-state and migrated paths. It fails without `0100`. - `populated_artifact_tables_auto_migrate_through_every_migration` checks that a channel head and revision written before `0097` survive with the same channel and event. - `artifact_unexpand_validates_while_channel_heads_are_written`: `0099` completes while a channel head write is still open. It fails if `0099` sets `NOT NULL` directly. - `artifact_unexpand_refuses_scoped_head_key`: `0098` stops on the scoped key and leaves `0097`'s columns in place. ## What got simpler The schema loses 5 unused columns and 3 unused indexes. `artifact_heads.channel_id` is required again, as the channel code assumes. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
4704fbafb6 |
fix(relay): resurface a hidden DM when someone else messages it (#9678)
## Summary A DM hidden with **Hide conversation** (kind 41012) stayed out of the sidebar for good, even after new messages arrived. The only way back was New message → same people → Send. This makes the relay clear the hide when *another* member posts a message (kinds 9 / 40002 / 40008) in the DM, like Slack does. The author's own hide is kept, so replying from another device doesn't resurface it. - `buzz-db` `dm.rs`: `unhide_dm_for_recipients` clears `hidden_at` for every other active member. `lock_dm_visibility` takes the same advisory lock that replacing the viewer's kind 30622 snapshot uses, then reads that viewer's hidden DMs and latest snapshot time. - `side_effects.rs`: `persist_dm_message` stores the message, clears the hides and replaces each affected viewer's snapshot in **one transaction**, then fans out after commit. A snapshot that doesn't land rejects the message, so the client's resend tries again. When someone hid the DM, the message takes the DM's membership lock before its insert, as a removal does, so it can't deadlock against a removal or reopen. The hide/open path (`publish_dm_visibility_snapshot`) shares the same lock → read → write seam. - Used by both message paths: client ingest (`ingest.rs`) and relay-signed workflow messages (`workflow_sink.rs`, author resolved via `effective_message_author`). - `NIP-DV.md`: documents the rule. **Deploy order:** relay first. The client companion is block/buzz-app#3889, which rereads visibility from the writer when a message lands in a hidden DM. Against an older client the row returns on the next roster refresh. ### Related issue N/A. None found. ### Testing - New Postgres test `dm_message_from_someone_else_unhides_it` (`membership_notice_postgres_tests.rs`): hide → the viewer's own message keeps it hidden → a peer's message whose snapshot is blocked by a trigger is rejected, not stored and not delivered → its resend, parked at fan-out, already shows the DM visible and is delivered once. It is `#[ignore]` (needs Postgres) and runs in Backend Integration CI. It was not run locally. - Pre-push `rust-tests` lane (`just test-unit`) and local clippy pass; `observability_source` source-policy test updated for the new transaction seam. - Reviewed by the Royal Court agents. Their findings (atomicity, lock-before-read, workflow path) are fixed in follow-up commits. - Human test pending. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Wes <wesbillman@users.noreply.github.com> Co-authored-by: Carl <32a2e2c9d428ee08902cab75d956da2c1d235a22d4766b0dd4138bf6e2e5db1d@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
b68c4edda5 |
feat(cli): show and search verified identity in users get (#9647)
## Summary `buzz users get` reads only kind:0 profiles, so the CLI can't find or confirm a person by their verified username. This adds relay-verified profiles (kind:30382) to `users get`. - `--pubkey` adds a `verified` object (`username`, `display_name`, `full_name`, `issuer_label`, `verified_at`) for subjects that have one. A requested person with a verified profile but no kind:0 is still returned. - `--name` uses the relay's `POST /profiles/search` when the community advertises verified profiles with `searchable: true`, so it matches verified names (word prefix). Otherwise, or for queries over the endpoint's 100-character limit, it runs the existing NIP-50 substring search and attaches verified profiles where the community advertises them. Verified profiles are read only when NIP-11 advertises `federated_identity.public_profile`. A projection is trusted only if it is kind 30382, signed by the relay's `self` key with a valid signature, and follows the NIP-FI projection rules the mobile client applies: empty content, exactly the projection tags (each once with one value), `p` equal to `d`, `active` set to `true`, a valid username, names of 1–64 characters with no surrounding whitespace or control characters (looser than mobile, which also requires NFC and rejects more Unicode categories), and a decimal `verified_at` no later than `created_at`. The newest projection per subject wins (the lower id breaks a same-second tie), so a retraction clears the verified name. Any `verified` key in user-authored kind:0 content is dropped on every path, so only a relay-signed projection can set it. `users get` now makes one NIP-11 request. If that request fails, the advertisement is malformed, or the kind:30382 lookup fails, it still prints the kind:0 results and writes a `verified_profiles_unavailable` warning to stderr. This applies to `--pubkey`, no args, and `--name`. ### Related issue Related: #8745 (verified profile spec), #9624 (verified-name mentions in workflows). ### Testing - `cargo test -p buzz-cli` passes, with tests for trust checks, retraction, both lookup paths, search without the advertisement, and a forged `verified` object in kind:0 (no advertisement, impostor-only projection, and a valid projection replacing it). - `cargo fmt` and `cargo clippy -p buzz-cli -D warnings` are clean. - An earlier revision of the built CLI was run against a live community with verified profiles: `--name <verified username>` found a user whose kind:0 name differs, and `--pubkey` returned the expected `verified` objects. --------- Signed-off-by: damienrj <damien@squareup.com> |
||
|
|
008d72a133 |
test(relay): stop bridge cancel_fixture tests timing out on the first replica connect (#9691)
## Problem All seven tests that share `cancel_fixture` in `crates/buzz-relay/src/api/bridge.rs` got a replica pool with a 1 s `acquire_timeout`. Only `shed_history_read_maps_to_503_on_every_bridge_branch` needs that budget: it holds the replica full and measures how fast a read sheds. sqlx applies `acquire_timeout` to opening connections as well as to waiting for a free one, so the budget also governed the fixture's initial connect and every later acquire that had to open a connection. A transient Postgres stall on the shared CI server therefore failed tests that never hold the replica full. CI showed `connect scratch: PoolTimedOut` at `bridge.rs:10309` in `aborted_history_read_logs_events_already_queued` and `failed_history_read_closes_and_reconnect_replays_the_history` (run 44205074529 shows eight tests finishing together after a ~3 s gap, which is the stall). Pools with sqlx's 30 s default waited the stall out; the 1 s replica did not. No connection leaked and the pool was not too small. The replica's 300 ms database-level `statement_timeout` had the same flaw: migrations and seeding ran under it, so a stall during setup failed `seed community` with 57014. ## Fix (test code only) - The six non-shed tests now use default pool budgets. - Only the shed test asks for the short budget, via `budgeted_reader`. That helper pre-opens all of the reader pool's connections under the 30 s default, and does not ping on acquire, so the 1 s budget covers only the wait for a free connection. - sqlx still pings each connection on release and closes it if the ping fails, so `budgeted_reader` waits until `num_idle()` equals `max_connections` before returning. A fill-and-drain loop (acquire to `max_connections`, drop, re-check) reopens any connection a failed release ping closed, under one 30 s deadline, and panics with the `N of M idle` count if the deadline passes. - The replica's `statement_timeout` is applied after migrations and seeding, and the replica is reopened so new sessions pick it up. - The shed test asserts each shed `/query` case completes in under 10 s, so a silent fallback to the 30 s default fails instead of passing slowly. ## Verification Reproduced locally by pausing the Postgres container for 2 s at random intervals while running `api::bridge::postgres_tests` at CI's 8 threads: `connect scratch: PoolTimedOut` appeared in 1 of 4 runs before the fix and in 0 of 8 after. With the fix, the 62 bridge postgres tests passed at 8 threads against a local Postgres (`--ignored`, including the shed, statement-cancel, and both history-read tests). `cargo fmt` is clean. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: mtoohey <mtoohey@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
a406191694 |
Revert "feat(relay): support community-scoped NIP-AR artifacts" (#9689)
Reverts #9650 (squash commit `eebf62b6`), except for migration `0097` and the channel artifact sync fences it added. Community scope adds a relay access gate based on community admission rather than channel membership, a new relay-admin command kind (`9034`) and an operator-run key transition. Its design and NIP-AR text need relay maintainer review before they ship. Two integration gaps also remain: - Media download authorization looks up references only in `events`, so an attachment referenced only by a community artifact is unreadable when media-read enforcement is on. - User erasure retires a community head in the database without signaling live syncs, so members who are already syncing keep the erased copy. The feature can return as a new PR once those are resolved. ## Kept from #9650 - **Migration `0097`, byte for byte.** Published images already include it, and databases that auto-migrated have recorded it. Dropping it would stop those relays from starting. It only adds columns and indexes that the channel code ignores. The declared schema matches that expanded shape and keeps the `(community_id, artifact_id)` primary key, so the operator key transition no longer exists. - **Channel artifact sync fences.** Snapshot and live sends check for a pending resync and for connection cancellation under the queue lock. A reader who loses access, or whose content is redacted, while a frame is in flight therefore receives no further payload. Handler-backed tests cover a resync recorded while a snapshot payload waits for queue room and one recorded after a live head read. ## Compatibility This revert supports databases that applied only migration `0097`, which is all that auto-migration runs. A database that ran #9650's operator contract script, or was bootstrapped from #9650's declared schema, has no `(community_id, artifact_id)` key, so channel artifact writes fail there. Before deploying to such a database, check that `artifact_heads_pkey` is on `(community_id, artifact_id)` and that `artifact_heads` has no rows with `scope = 'community'`; if either check fails, it needs a separate recovery step. --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Paul <4a1bfa0013bc6d14a8d600d8bf6392efefbd2a26ac3c96c9b2a106b0d12297ca@buzz.block.builderlab.xyz> |
||
|
|
db40da87b4 |
feat(relay): add conditional Solo member role updates (#9667)
**Category:** improvement **User Impact:** Solo chat owners can lower the access of any current non-owner, including people and agents. **Problem:** Using invitations to change Solo chat access can restore a removed member, reject a downgrade because of the target’s invitation policy, or show a join notice for a role change. **Solution:** Add signed role updates that require an active member at the expected role when the relay commits the change. A Solo owner can downgrade any current non-owner. Moving a viewer to Participating requires a verified agent, and granting Admin requires ownership of that agent. The relay refreshes signed group state without emitting a join notice. Companion to [block/buzz-app#3704](https://github.com/block/buzz-app/pull/3704). The [app review](https://github.com/block/buzz-app/pull/3704#pullrequestreview-5962147206) identified the need for conditional writes, verified agent identity and live relay validation. [#9592](https://github.com/block/buzz/pull/9592) introduced the atomic removal that uses the same membership lock. <details> <summary>File changes</summary> **crates/buzz-core/src/kind.rs** Register signed Solo role updates as kind 9050. **crates/buzz-db/src/store/channel_members.rs** Authorize the transition under the channel membership lock and commit the active row update and signed event together. **crates/buzz-relay/src/handlers/event.rs** Give the new command a bounded metrics label. **crates/buzz-relay/src/handlers/ingest.rs** Use the shared signed ingest path and require the channel administration scope. **crates/buzz-relay/src/handlers/mod.rs** Register the command handler and its PostgreSQL test. **crates/buzz-relay/src/handlers/solo_member_role.rs** Parse the command, route it to the conditional write, and refresh signed group state after commit. **crates/buzz-relay/src/handlers/solo_member_role_postgres_tests.rs** Exercise human and agent changes, restrictive invitation policy, promotion authorization, stale and removed membership, duplicate receipt, and signed roster updates through the relay’s production ingest path. **docs/solo-mobile-contract.md** Describe the wire format, permitted transitions, and handling when an older relay rejects the command. </details> ### Try it 1. Run the updated relay and the companion app against a disposable Solo chat with a current human and agent. Open **Chat access** as the owner. 2. Lower the human to **Viewing only**. Reopen **Chat access** and confirm the saved role. A role change should produce no join notice. 3. Downgrade an agent with a restrictive invitation policy. Confirm its role changes. Check that **Admin** can be granted only to your own verified agent. 4. Run `solo_owner_edits_active_members_and_publishes_the_new_roster` with PostgreSQL to check that a pending change for a removed member is refused and the signed roster stays clear of that member. ### Validation - The PostgreSQL regression passes at relay commit `405f7d1da`. It covers role and invite-policy enforcement, signed roster refresh, duplicate receipts, and rejection after removal. - The companion app at `a470947dc6` passes 138 administration tests. Its production command builder, validator, and signed roster reader also passed over WebSocket against a local relay backed by PostgreSQL and Redis. A human moved from Admin to Participating to Viewing only, then was removed. The app preflight and relay both refused a further role edit, and the signed roster still excluded the member. - The live check exercised the app’s relay code headlessly. The UI walkthrough is pending. --------- Signed-off-by: Taylor Ho <taylorkmho@gmail.com> Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: Carl <acda9e433d19dcd0e6b6840f7f4b98f3a56f1fab98049d444c087019e6d36560@feedback.communities.buzz.xyz> Co-authored-by: Tom Brow <tomb@block.xyz> |
||
|
|
eebf62b61d |
feat(relay): support community-scoped NIP-AR artifacts (#9650)
## Summary NIP-AR clients can store community-scoped artifacts and subscribe to live changes for one exact artifact type. Community and channel artifacts share revision and retry semantics and use separate identity scopes. Community owners and admins can choose whether a type accepts edits from all admitted members or only administrators. This PR combines the protocol from #9638 with the relay implementation. [Protocol]( |
||
|
|
44e97e96f4 |
fix(pubsub): round the rate-limit retry hint up from PTTL (#9552)
## Summary The Redis rate limiter built its `retry in Ns` hint from `TTL`, which truncates to whole seconds. With 400 ms left in the window, a denied request was told `retry in 0s`, and a client that sleeps for exactly the hint retried straight into another refusal. This reads `PTTL` and rounds the milliseconds up to whole seconds, so the hint is never 0 while the window is still open. The no-expiry repair path is unchanged. ## Testing - New `rate_limiter::tests::retry_hint_rounds_a_partial_second_up` (`#[ignore = "requires Redis"]`, like the other Redis tests in this crate) seeds an exhausted window with 400 ms left and asserts the denial reports 1 second. Against the old `TTL` code it fails with `left: 0, right: 1`; with this change it passes. - `cargo nextest run -p buzz-pubsub --lib`: 38 passed. Ignored Redis `rate_limiter` and `nip98_replay` tests: 5 passed against a local Redis. - `cargo nextest run -p buzz-relay --lib` with local Postgres and Redis: 1762 passed. The relay `rejection::`/`admission::` lane with `--run-ignored all`: 16 passed. - Pre-push hooks (including rust-tests) passed. CI note: the Redis-backed pubsub tests only run in CI when they are named in `.github/workflows/_ci-relay.yml`, so the new test isn't selected there yet. Adding `or test(/^rate_limiter::tests::/)` to the "Pubsub subscriber reconciliation regression" filter would cover it. I left that out here because this branch can't push workflow file changes. --------- Signed-off-by: Wes <wesb@block.xyz> Co-authored-by: Groot <f4c08302591916fb4b80926bf7e18d22eef8aa0c877e4e841acc46405a45700b@buzz.block.builderlab.xyz> Co-authored-by: Star Lord <b89298dbe87c6b3fd8a425b535d9d161f23c88d555a47925ae0b04dfe02b201e@buzz.block.builderlab.xyz> |
||
|
|
8d613ce0e8 |
test(relay): refresh the author's membership cache after the stray-h private channel insert (#9640)
Fixes `handlers::ingest::postgres_tests::reaction_and_deletion_h_must_name_the_target_channel`, which fails on main in the PostgreSQL Tests jobs. The test creates its private channel directly in the database after the author has already published, so the per-user membership cache (`is_member_cached`) still holds the author's snapshot from before that channel existed. The author's post to the new channel is then refused with `restricted: not a channel member`. The test now drops the author's cached membership after the insert, so the channel's owner is seen as a member. The test's assertions are unchanged. Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> |
||
|
|
7cf19b713c |
perf(db): bound deep keyset history pages by the cursor timestamp (#9549)
## Problem `query_events` and `get_channel_window` page history with a composite `(until, before_id)` cursor under `ORDER BY created_at DESC, id ASC`. The cursor predicate was only: ```sql created_at < $u OR (created_at = $u AND id > $bid) ``` PostgreSQL cannot use that OR as the start of an index range, so a page deep in a channel walks the `(community_id, channel_id, created_at DESC, id)` index from the newest row and filters every newer row before it reaches the page. The cost of a page grows with its depth. ## Fix Add the redundant bound `created_at <= $u` next to the OR in both queries (`store/event.rs` and `store/thread.rs`). It does not change which rows match; it gives the planner an `Index Cond` range start at the cursor. This is the same bound the thread window query already carries (`store/thread_window.rs`). `api/bridge.rs` has the pattern only in a test fake that emulates `query_events_on`; the bridge itself routes cursors into these two store functions, so it needs no change. ## EXPLAIN before / after `EXPLAIN (ANALYZE, BUFFERS)` of the `query_events` page shape, `LIMIT 51`, kind 9, by cursor depth. Copy of a real channel (2,277 messages), custom plan, shared buffers hit: | Depth | Before | After | | ---: | ---: | ---: | | 50 | 96 | 96 | | 300 | 311 | 84 | | 1,000 | 969 | 80 | | 1,500 | 1,443 | 92 | | 2,100 | 2,006 | 89 | At depth 2,100: execution 0.709 ms to 0.058 ms, rows removed by filter 2,101 to 42. With a generic plan the after numbers are also flat (80 to 96 buffers at every depth). Synthetic table (one channel with 20,000 kind-9 rows plus 20 other channels of 2,000 each): | Query | Depth | Before | After | | --- | ---: | ---: | ---: | | `query_events`, custom plan | 10,000 | 701 | 11 | | `query_events`, generic plan | 50 | 874 (7.5 ms) | 11 (0.11 ms) | | `query_events`, generic plan | 10,000 | 444 | 11 | | `get_channel_window`, custom plan | 10,000 | 1,006 (2.35 ms) | 312 (0.49 ms) | | `get_channel_window`, custom plan | 19,940 | 1,690 (4.35 ms) | 314 (0.47 ms) | For `get_channel_window` at depth 19,940 the events index scan went from 1,385 buffers and 19,941 rows removed by filter to 9 buffers and 4 rows; the rest of its plan is the thread metadata join, which is unchanged. On the small 2,277-row channel the planner picks a sequential or bitmap scan for the window query, so its plan is unchanged there. ## Tests New Postgres test `store::event::postgres_tests::deep_keyset_pages_read_from_the_cursor`: - Inserts 1,000 kind-9 rows into one channel, two per second, so the cursor lands on same-second ties. - Turns off sequential and bitmap scans for the session, so the small fixture uses the ordered index walk a large channel uses, then reads one 50-row page at depth 900 through both `query_events_on` and `get_channel_window_on`. It asserts each page equals the expected rows and that each read touched at most 150 event rows (summed `seq_tup_read + idx_tup_fetch` over the `events` partitions). - Pages the whole channel through both paths and asserts every row comes back once, in order. Checked by reverting each half of the fix: - `event.rs` bound removed: `events page at depth 900 read 950 rows for 50` - `thread.rs` bound removed: `window page at depth 900 read 1000 rows for 50` - With the fix: passes (5 of 5 under `--stress-count 5`), reading 52 and 53 rows. Runs: - `scripts/postgres-test-run.sh -p buzz-db --lib --tests`: 763 run, 756 passed. The 7 failures were the new test before its final fixture change (it now passes) and 6 that fail the same way on unmodified `main` in my environment because they spawn a host `psql` binary that isn't installed there: `migration_schema_media_prebuild_waits_for_old_transactions_during_creation_and_cleanup`, `script_stops_at_the_first_auth_refusal`, `script_renames_each_planned_channel_once_whatever_its_name`, `desired_event_follow_up_contract_app_only`, `desired_event_follow_up_contract_dual`, `migration_schema_event_follow_up_contract_app_only`. CI's Postgres lane is the authoritative run for those. - On the final head: the new test plus every `channel_window` Postgres test, 9 of 9 passed. - `cargo nextest run -p buzz-db --lib` (no infrastructure): 216 passed. `--test observability_source`: 28 passed. Doc tests: 5 passed. - `scripts/test-postgres-test-discovery.sh`: passed. - Pre-push `rust-tests` lane: passed. ## How to test 1. Run `scripts/postgres-test-run.sh -p buzz-db --lib -E 'test(deep_keyset_pages_read_from_the_cursor)'`. 2. Optionally, in a database with a channel of a few thousand messages, open the channel in a client and scroll back through history. Older pages should load as quickly as the first ones, and no message should be skipped or repeated across page boundaries. ## Related No duplicate PR or issue found. Related: #1787 (keyset index for thread replies) and #6004 (CLI wiring for the composite cursors). Signed-off-by: Wes <wesb@block.xyz> Co-authored-by: Groot <f4c08302591916fb4b80926bf7e18d22eef8aa0c877e4e841acc46405a45700b@buzz.block.builderlab.xyz> |
||
|
|
11970789eb |
feat(cli)!: consistent channels list/get/search output (type, visibility, labels, real created_at) (#9617)
Closes #6390 ## Summary `buzz channels list`, `get` and `search` each projected kind:39000 channel metadata differently. `list`/`get` dropped the classification tags, so a script couldn't tell a Solo chat from a stream or a private channel from an open one. The three commands also disagreed on field names, defaults and empty values, and `created_at` reported the last-edit time (#6390). All three now print one `ChannelSummary`, with `pubkey` added on `get`: | Field | Source | |---|---| | `channel_id`, `name` | `d`, `name` tags | | `channel_type` | first `t` tag (`stream`, `forum`, `dm`, `workflow`, `system`) | | `visibility` | `open` for `["public"]`, `private` for `["private"]` | | `labels` | the `t` tags after the first, e.g. `["buzz.solo"]` | | `archived` | `["archived","true"]` | | `description` | NIP-29 `about` tag | | `topic`, `purpose`, `ttl_seconds` | `topic`, `purpose`, `ttl` tags | | `created_at` | the channel's `created_at` tag (NIP-CL), or `null` when absent | | `updated_at` | the event's own `created_at`, which is the last metadata change | Compact `list` output (`{channel_id, name}`) is unchanged. ### Breaking output changes These are intentional, and they were discussed with a maintainer before this change: - **`search`:** `about` is renamed `description`, matching `list`/`get` and `create`/`update --description`. - **`list`/`get`/`search`:** `created_at` is now the real creation time. The old value, the last-edit time, moves to the new `updated_at`. - **`list`:** archived channels are hidden by default, as `search` already did. The new `--include-archived` flag shows them. `get --channel <id>` still returns an archived channel. `--limit` (and `--visibility`) count the channels printed: `list` reads past filtered channels, bounded by `MAX_QUERY_PAGES` on the default path and by 10,000 memberships with `--member`. - **Missing values:** they print `null` instead of `""`. This mainly affects `description`. - **`visibility`:** it prints `open`/`private`, the values `--visibility` takes, instead of the raw `public` tag. `search` printed `public` before. No in-repo consumer reads the renamed fields or the `public` value. The benchmarks read `search`'s `channel_type`, `visibility == "private"`, `archived` and `ttl_seconds`, all of which are unchanged. ### Related - Closes #6390. - Overlaps with #5664 and draft #6353, which add type and visibility to `list`/`get`. This PR covers both: it uses `open` like #6353, plus labels, archived, parity and the `created_at` fix. A maintainer may want to close them as superseded. Unlike #6353, it doesn't error on missing or contradictory visibility tags, so one malformed channel can't fail a whole `list`. ### Testing - `cargo test -p buzz-cli`: 699 passed. Clippy is clean. The tests build events from the captured `test-fixtures/solo-creation.json` identity tags and pin the full JSON shape, including the all-`null` case. They also cover the production `listed_channels` and `search_matches` filters: archived hiding, `--visibility`, and search's name and ID requirement and ordering. - An agent ran the changed commands against a live relay: - `get` and `search --exact` return identical fields for the same channel. - Over 2,000 channels, `list` hides 162 archived channels unless `--include-archived` is passed. - `--visibility open` returns only `open` channels. - 1,777 channels have `created_at < updated_at`. - No `description` is `""`. - Compact output is unchanged. - `list --limit 10` and `--member --limit 5` return exactly 10 and 5 non-archived channels, and `--limit 2000` returns 2,000 with none archived. - An independent agent review found no blockers. Its one cheap nit, `get` printing `pubkey: ""`, now prints `null`. - The pre-push workspace `rust-tests` lane was skipped for this push. When the push was made, `origin/main` didn't compile `buzz-db`'s lib tests, which is unrelated to this `crates/buzz-cli`-only diff. That breakage has since been fixed on main, so CI runs the full workspace. buzz-review-completed 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Jemiah Westerman <jemiah@squareup.com> Co-authored-by: Son of Anton <8e0ef2ab02d69a7ac089ef5eca90d1a3fbbdc546f6322dc34d0c4f3deecea7f4@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
493cb4cc13 |
perf(db): stop per-id planning of wide #e reads (#9591)
Thread pages fetch the reactions, edits and deletions of ~200 ids at once. Until a pooled connection has run that `#e` read about five times, Postgres plans it with the values: ~12 ms per plan (one estimate per id per partition) against ~2 ms to run it. Past 8 ids the arrays now go through a scalar subquery, so planning is one estimate (~1.5 ms) and still uses the tags GIN index; narrower reads are unchanged. On an 830-reply local thread, one viewer's full scan drops from 119 to 59 ms p50; with 50 viewers p50 holds at 242 ms, p99 drops from 664 to 413 ms, and the read's planning time falls from 13 s to 0.6 s per minute. --------- Signed-off-by: Sanket Kanjalkar <sanketk@squareup.com> |
||
|
|
25b58ab98f |
feat(push-gateway): verify Android Key Attestation (#9562)
## What and why Ticket 3 of the Android push plan ([design PR #9555](https://github.com/block/buzz/pull/9555)). The gateway now verifies Android Key Attestation at enrollment instead of rejecting every Android chain, and rate limits signed installation calls per attested key. Stacked on [#9560](https://github.com/block/buzz/pull/9560) (Android enrollment and FCM wakes). This PR's base is that branch; it will be retargeted once that merges. - **Chain.** It must end at a configured Google attestation root (Google's [published hardware roots](https://developer.android.com/privacy-and-security/security-key-attestation#root_certificate) are built in, pinned by public key), with valid signatures and issuer links, CA issuers above the attestation key certificate, and no SHA-1 signatures. The attestation key certificate itself is exempt from the CA flags, because some factory keyboxes issue it with CA:FALSE and digitalSignature only (Google's Sony Xperia 10 III sample); a Keystore leaf still cannot act as an issuer, since the extension is refused above the leaf. Validity is enforced for Remote Key Provisioning chains; Google tells verifiers to keep trusting the long-expired factory chains, which the revocation list covers instead. The attestation extension must be in the leaf and nowhere else. The leaf key must be EC P-256; it becomes the installation's signing key. - **KeyDescription.** Attestation and KeyMint security levels must be TrustedEnvironment or StrongBox. The challenge must equal SHA-256 of the enrollment transcript. Key properties (generated, EC, P-256, sign-only) and the root of trust come only from the hardware-enforced list. The bootloader must be locked, and the boot state Verified, or SelfSigned with a verified boot key on an operator-configured list. The application id (the one software-enforced value) must name exactly the configured package with a configured signing digest. - **Revocation.** A background task fetches Google's status list at startup and then on its cache lifetime (5 minutes to 1 day), with a 30 second timeout, an 8 MiB size cap, capped exponential backoff and jitter. Any REVOKED or SUSPENDED serial in the chain is rejected. With no list yet, or a list older than the grace period, enrollment fails closed. Enrollment reads an in-memory snapshot and never waits on a fetch. - **Rate limit.** Signed installation calls (delegate, revoke delegation, rotate endpoint, revoke installation, on both platforms) are limited per attested key. A call is counted only after its signature verifies, so forged requests cannot spend another installation's allowance. Counters are in memory per replica, bounded to 100,000 keys. - **Dependencies.** None added. `x509-parser` gains its `verify-aws` feature, which uses the `aws-lc-rs` the crate already depends on. ## Configuration All optional; Android stays off unless the ticket 2 settings are present. Documented in `docs/push-gateway-deployment.md` and `.env.example` with example values only, and passed through `deploy/charts/buzz-push-gateway` (disabled by default, schema-checked, covered by `tests/runtime-options.sh`). - `BUZZ_PUSH_ANDROID_BOOT_KEY_DIGESTS`: SHA-256 digests of verified boot keys accepted with a SelfSigned boot state. Empty by default, so a default gateway accepts stock Android only. - `BUZZ_PUSH_ANDROID_ATTESTATION_ROOTS_PATH`: PEM bundle replacing the built-in roots, for a reviewed root rollout. In the chart, `android.attestationRoots.secretName` and `secretKey` mount it from a Secret; an empty name keeps the built-in roots. - `BUZZ_PUSH_ANDROID_REVOCATION_GRACE_SECONDS`: default 604800 (7 days), minimum 3600. - `BUZZ_PUSH_SIGNED_CALL_WINDOW_SECONDS` and `BUZZ_PUSH_SIGNED_CALL_MAX_CALLS`: defaults 60 and 30. ## Tests - `cargo test -p buzz-push-gateway` (all pass, 18 ignored), `cargo fmt --all --check`, `cargo clippy -p buzz-push-gateway --all-targets -- -D warnings`, and the chart tests (`render.sh`, `release-contract.sh`). - Key Attestation chains are generated in the tests with a test root injected as the configured root, and run through the production verifier. One table rejects: unlocked bootloader, Unverified, Failed, SelfSigned with an unlisted key, boot key only in the software list (two variants), key properties only in the software list, extra key purposes, wrong curve, wrong package, two packages, wrong signing digest, wrong challenge, software-backed key (two variants), unknown root, forged leaf signature, expired provisioned intermediate, extension repeated above the leaf, non-P-256 leaf, a CA:FALSE certificate issuing the attestation key certificate. Another accepts Verified with any boot key, SelfSigned with a listed key, StrongBox and TrustedEnvironment, an expired factory intermediate, and a CA:FALSE, digitalSignature attestation key certificate. Revoked leaf, intermediate and root, a missing list and a stale list are rejected. The status list parser and refresh (backoff, cap, keeping the last list through failures) run against a scripted fake source; no test touches the network. - The per-key rate limit runs through the public router: forged calls do not spend the allowance, the fourth authentic call is refused whatever its kind, and another installation is unaffected. - Break check: disabling the locked-bootloader guard and the rate limit turned `rejected_attestations` and the rate limit test red; restored. ## Not here The app side (ticket 7) generates the Keystore key and sends the chain. The end to end run on a physical Android phone against a test gateway is also still to do. --------- Signed-off-by: Tom Brow <tomb@squareup.com> |
||
|
|
b769d5bee8 |
fix(relay): remove an owner's agents with the owner (#9575)
## What this changes When someone is removed from a community, their agents' live sessions already closed, but the agents kept their own membership rows and could reconnect as members. This PR removes those agents with their owner. - **Cascade.** `delete_member_with_acceptances` locks and deletes the target, then locks and deletes the `join_policy_acceptances` and `relay_members` rows of every member of the same community whose `users.agent_owner_pubkey` is the target and whose role is not `owner`. All of it runs in the same transaction, before the roster snapshot is written. Admin removal (kind 9031), self-leave and `buzz-admin remove-member` all go through it. An agent goes with its owner whatever its role, so an admin who removes a member also removes that member's admin-role agent. A direct 9031 target is still limited to `member` for admins. - **Owner recording.** The relay records a verified NIP-OA owner on every admitted sign-in, whatever the relay mode or `allow_nip_oa_auth`: on WebSocket AUTH, and for HTTP in the shared admission step after the denial checks, so `/events`, `/query`, `/count` and member POSTs all record it in one place. Before, it recorded only on open relays, so on closed relays the cascade and owner bans missed agents added directly. A request refused before recording writes nothing. Once the owner-signed tag is verified and the first admission checks pass, the relay may record the owner even if a final check, a cancellation or a token revocation then refuses the sign-in. The record still can't be changed. Over HTTP, a different stored owner refuses the request with 403 (invite creation keeps its `invite_owner_mismatch` code), and storage trouble refuses it with 503. A recorded owner can also manage the agent (channel management, channel-add policy, invites). - **CLI.** `buzz-admin remove-member` publishes clusterwide disconnects (`ConnControl::DisconnectPubkey`) for the target and its recorded agents on every run, including when the member is already gone. If publication fails or no relay server is subscribed, it exits 6 after the removal commits. Rerunning the same command retries the disconnect. - **Spec.** NIP-FI states the rule. ## Rollout limit An agent is covered only if its owner was recorded before the owner is removed. An agent whose owner was removed before the agent signed in with a NIP-OA tag after deploy, or an agent that never signs in with one, stays a member and needs a manual removal. The relay holds no proof of ownership for those agents, so there is nothing to backfill. Supersedes #6098 and #6078. --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> |
||
|
|
4bf7d8a9b0 |
relay: refuse a reaction or deletion whose h names another channel (#9006)
## Summary A reaction, or a deletion that targets a message, belongs to the target message's channel. The relay works out that channel from the target and stores the event there. But every read and every live delivery matches the event's own channel (`h`) tags. So if a client puts a *different* channel in the `h` tag, the event is stored in one channel and only ever matches another: - No one ever receives it. - It still takes a slot when a client asks for "the latest N events" of the real channel. A catch-up can then return fewer events than exist while it looks complete, because the relay removes the stray event after it applies the limit. This is one of the known gaps in https://github.com/block/buzz-app/pull/2206. The relay now refuses such an event. The rule: | Event's `h` tags | Before | After | |---|---|---| | none | accepted | accepted | | include the target's channel | accepted | accepted | | only other channels | accepted, never delivered | refused | The refusal uses the same "target not found" text as the existing refusals for these kinds. So it tells the sender nothing about where the target is. No first-party client sends a mismatched `h`. buzz-app uses the target message's channel, and desktop, mobile and the SDK send no `h` on reactions. So no current client is affected. ### Details - The check covers kind:7 reactions and kind:5 deletions that name their target with an `e` tag. These are the two kinds whose channel comes from a target. A kind:5 that names an addressable event (`a` tag) is not affected. - The check runs only when the target is in a channel, so a reaction to a global event keeps any `h`. A tag must be the channel's UUID exactly as the relay writes it (lowercase, hyphenated), the same way `#h` filters match. - The check runs after the token, membership and archive checks. If it ran first, it would skip their database reads, and the response time could tell someone who cannot read a private channel whether a guessed `h` names the channel that holds a message. - Events already stored with a stray `h` are not changed. They can still take a slot under the limit. - NOSTR.md now says that an optional `#h` on these kinds must name the target's channel. It also says kind:5 takes its channel from its `#e` target (the old text said it used `#h`). ### Related issue None found. Follow-up to the known gaps listed in https://github.com/block/buzz-app/pull/2206. ### Testing - New `reaction_and_deletion_h_must_name_the_target_channel` test, as a member of the target's channel. A reaction whose `h` names only another channel is refused and not stored. A reaction with no `h`, or with both channels, is accepted, and so is a reaction with any `h` on a global event. A deletion of that reaction is refused and not stored with another channel's `h`. It is accepted with the target's `h` or with no `h`. A non-member's wrong guess still reaches the membership check. On a private channel, a right guess and a wrong guess both end at the same membership denial. - I removed the check, and the test failed. I also moved it back before the membership check, and the test failed. - On a local relay over WebSocket: the same refusals and acceptances, with the same messages, and a reaction to a global event keeps its `h`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Human test: Logan asked to take this to team review without a separate hand test (2026-11-17). buzz-review-completed Signed-off-by: Logan Johnson <loganj@squareup.com> Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz> |
||
|
|
3876720c34 |
buzz-db: drop the five single-table guard triggers (BUZZ-318 phase 2) (#9398)
> [!NOTE] > **Rollout:** #8320 (app guards + catalog expand) is deployed, so the hold is lifted. With `autoMigrate=true`, `0096` runs at startup under a 5s lock timeout, and a failure stops startup. With `BUZZ_AUTO_MIGRATE=false`, deploy this binary first and then run `buzz-admin migrate`. Both orders are safe because the expand tolerates the objects being present or absent. ## What The required stop for `0096` is in `docs/trigger-retirement-deployment.md` (from #9622): a relay build at or after #8320 (`ec778bff`). A build older than that needs the tombstone trigger at startup and readiness. Migration `0096_drop_single_table_guards.sql` drops five triggers and their functions. #8320 moved each invariant into the application writers: | Trigger (table) | Function | |---|---| | `trg_channels_community_id_immutable` (channels) | `channels_community_id_immutable()` | | `communities_deletion_tombstone` (communities) | `enforce_community_tombstone()` | | `community_deletion_request_retargeting_guard` (community_deletion_requests) | `prevent_community_deletion_request_retargeting()` | | `community_deletion_approval_removal_guard` (community_deletion_approvals) | `prevent_community_deletion_approval_removal()` | | `community_deletion_manifest_keys_guard` (community_deletion_manifest_keys) | `protect_community_deletion_manifest_keys()` | Desired state (`schema/`) drops the five functions and four trigger files, plus the channels trigger declaration. The universal write fence on `channels` stays. Both boot paths stay catalog-equivalent: the pgschema-vs-migration parity check now also compares columns, key and FK shapes, and the remaining triggers on all five tables. Executor GUCs stay because `assert_community_write_allowed` still reads them through the universal write fence. `transition_community` and every phase-1 app guard are byte-identical to #8320. `scripts/reconcile-schema-after-pgschema.sql` has no entries for these objects. ## Tests - #8320's six `single_table_guard_*_without_trigger` PG tests no longer need to disable a trigger. They are now plain app-path tests with the same assertions. - New per-test regressions for the desired-template and migration boot paths assert that none of the ten objects exist, including disabled triggers and function overloads. - Deleted assertions that only exercised raw SQL against the triggers: retarget, rewrite and approval mutation, frozen-manifest rewrite, and tombstone DELETE. The app-path coverage for each remains. - The expand regression in #8320 migrates through `0086`, validates serving, readiness and the deletion lifecycle, drops the five guards, then validates again. - Rebased onto main `b568d9bf` after #8696 took `0095`; renumbered to `0096`. Blox gate at `7bda1f45`: fmt, clippy and buzz-db `--lib` pass; the PostgreSQL lane ran 219 tests, all pass. - Gate at `c8bc061c` (on main `051dd2d7`, then numbered `0095`, #9622 folded in): on Blox, `cargo fmt --check`, clippy and the buzz-db `--lib` tests pass. The PostgreSQL lane (migrations, single-table guards, floor retirement, fence and deletion) ran 208 tests: all pass. - Earlier gate at `0840ba49`: CI was green, and the Blox PostgreSQL lane passed 840 of 841 (the one failure, `media_reference_full_query_plans`, is a timing check that fails the same way on main on that host). - The rebase updates main's fence-retirement tests to expect the tombstone trigger gone. ## What got simpler Ten database behavior objects and nine desired-state files are gone (about 150 lines). Each rule has a single owner, the application writer. buzz-review-completed 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Luke Tornquist <tornquist@squareup.com> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Tom Brow <tomb@block.xyz> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> |
||
|
|
44cdd9feef |
push-gateway: lock expired installations before reaping (#9627)
## What The push gateway reaper deletes expired delegations and then expired installations in two statements. A delegation writer (`upsert_delegation`) that holds the installation lock can commit a new child between them. With the foreign key, the installation delete then fails, and the reap transaction rolls back. This PR locks the expired installations with `FOR UPDATE` first, as every authority mutation does. It then deletes their delegations and the installations by id. A writer that was holding the lock commits first, and the delete sees its child. A later writer finds the parent gone and is rejected. No schema change. This is the code half of #9610. The gateway image with this change must run everywhere before the delegation foreign key is dropped. ## Tests Blox at `20b66f8f`: fmt, clippy, and the push-gateway PostgreSQL tests (15/15) pass. - `reaper_deletes_delegation_committed_while_it_waits`: a writer holds the installation lock and inserts a child. The reaper starts and waits. The writer commits. The reaper deletes both rows. - `delegation_for_missing_installation_is_rejected`: `upsert_delegation` for an unknown installation returns `Rejected` and writes nothing. ## What got simpler The reaper now uses the same lock order as every other authority write. The child delete no longer needs a correlated subquery. buzz-review-completed 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
b568d9bf95 |
Retire the 0032 roster trigger in migration 0095 (#8696)
## Summary Migration 0095 drops the 0032 channel roster trigger (`trg_events_guard_channel_roster_snapshot`) and its function (`guard_channel_roster_snapshot()`). The trigger repeats a check that the relay already does in Rust. Every kind:39002 roster writer checks the roster against the channel's membership before it saves it (#8316). Since #8611, no relay requires the trigger at startup. This PR is the last step of the trigger retirement sequence in `docs/database.md`. This PR was split out of #8494 so the migration can roll out by itself. A relay from this PR does not change how it stores or publishes roles, and it has no new startup check. It serves correctly whether or not 0095 has run. #8494 stacks on this PR and must not merge until 0095 has run in every environment. ## Details - **Migration 0095.** `DROP TRIGGER` and `DROP FUNCTION`, with `lock_timeout = '1s'` and `statement_timeout = '5s'` as in 0049. `DROP TRIGGER` takes `ACCESS EXCLUSIVE` on each `events` partition in turn, so event reads and writes block while it runs. A timeout rolls it back with no change, and it can be retried. - **Desired-state schema.** `schema/functions/guard_channel_roster_snapshot.sql` is removed. This was the last trigger on `events`, so `schema/triggers/events.sql` and its include go too, as do the pre-attach trigger drops in `scripts/reconcile-schema-after-pgschema.sql`. - **Operator guide.** #8326 added `docs/trigger-retirement-deployment.md` for migrations 0089–0091. (0092 from #9365 and 0093 from #9560 drop nothing; 0094 from #9598 drops two plain SQL functions and has its own section there.) This PR adds 0095 to it: its row, the two ways an older relay fails, the migrate check, and the parent trigger a pgschema deployment must drop first. The Helm chart README names the required stop and points to that guide. - **Tests.** Tests that compared the trigger with the Rust check, or that disabled the trigger first, now test the Rust check alone. Tests that only exercised the trigger against a simulated pre-#8316 writer are removed. The 0075 invite upgrade test now migrates to 0075 exactly. ## Rollout **Required stop: the stop build in `docs/trigger-retirement-deployment.md`** (a relay build at or after `68785206`, the merge of #8325). That build contains #8316 (the app-side roster check) and #8611 (no startup trigger check), so it covers 0095 too. `relay-v0.3.0` contains #8316 and #8611 but not #8325, so it is no longer enough on its own: any build with 0095 also has 0089–0091. Without the stop, an untagged `main` build between 0032 and #8611 refuses to start once the trigger is gone, and a relay without #8316 can save stale kind:39002 snapshots (`docs/database.md` Rule 5). **Merge gate.** Every push to main publishes relay `:main` images, and the Helm chart defaults to `migrate.autoMigrate=true`. Do not merge this PR until the stop build or later runs on every serving and rollback target. That is the same gate #8326 had for 0089–0091. After that, either way works: - With `autoMigrate=true`, the first relay from this PR applies 0095 at startup. - With `autoMigrate=false`, run `buzz-admin migrate` when convenient. Relays from this PR serve with or without 0095. As with every new migration, an older binary with auto-migration on refuses a database that has 0095 (sqlx `VersionMissing`). A rollback past this release needs auto-migration off (`docs/database.md`). ## What happens next #8494 computes the `member`/`bot` label at read time. The 0032 trigger compares labels with the stored role exactly, so it would refuse those rosters. #8494 adds a startup check that refuses to serve while the trigger is installed. Merge it only after 0095 has run everywhere. ### Testing - `migration_0095_retires_the_roster_trigger`: on a database migrated through 0094, the trigger and function are installed. After the remaining migrations, both are gone, and a raw kind:39002 insert that does not match membership is accepted. It fails if 0095 does not drop them. - `embedded_migrator_contains_consolidated_initial_schema` pins 95 migrations and the 0095 statements, and checks that the desired-state schema no longer installs the function. - `migration_schema_desired_pgschema_reconcile_matches_populated_upgrade`: its fixture drops each retired parent trigger before pgschema runs (pgschema drops partition copies before the parent, which PostgreSQL refuses with 2BP01). It now drops the roster trigger too. - Locally at this head: `cargo check`, `cargo fmt --check`, and 245/245 buzz-db unit tests pass; 760/764 buzz-db Postgres tests pass. The four `event_follow_up_contract` tests fail the same way on `main` locally and pass in CI. CI runs clippy and the full PostgreSQL lane. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Logan Johnson <loganj@squareup.com> Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
c01d3292a1 |
fix(db): hard-delete superseded relay-signed lists (#9586)
## Why
The relay republishes its own lists in full on every change:
- the NIP-43 membership list (kind 13534)
- the NIP-IA archived list (13535)
- NIP-29 group state (39000 metadata, 39001 admins, 39002 members)
Each write soft-deletes the previous head. No reader returns a
soft-deleted row, so each retired copy is dead weight in `events` and
its indexes. On the deployments we measured, these retired copies are
about 40–65% of monthly `events` growth. The NIP-33 path already
hard-deletes superseded NIP-RS read state and mesh status in the
replacing transaction. This PR applies the same rule to the relay-owned
lists.
## What
When a write supersedes a head of kind 13534, 13535, 39000, 39001, or
39002, it deletes the old head instead of soft-deleting it. The delete
runs in the same transaction, under the same scope and lock as before.
The change applies on the 3 paths the relay uses to write these kinds:
- `replace_addressable_event_under_lock` (13535, 39000, 39001, including
`buzz-admin` writes through `replace_addressable_event`). It gates on
the new `hard_deletes_superseded(kind)`. Other kinds on this path (0, 3,
10002, …) keep the soft delete.
- `LockedMemberSnapshot::replace_member_event` (39002).
- `write_nip43_membership_snapshot` (13534).
All 3 paths build their head read and supersede statement with one
function, `replacement_sql(in_channel, hard_delete)`, keyed by
`hard_deletes_superseded(kind)`.
Kind 13535 is now relay-only: ingest rejects a client-submitted 13535
with `restricted: relay-only kind`, as it already does for 13534. NIP-IA
defines 13535 as relay-signed, and every relay, desktop, CLI, and mobile
reader filters on the relay's pubkey. No client in this repository
publishes it.
The 39000–39002 paths already use `superseded_with_mentions_sql!`, so
the old head's mention rows are deleted with it, as before.
The gate checks the kind, not the signer, and every supersede is scoped
to the event's own pubkey. A client-signed 39000–39002 is routed to the
NIP-33 path, which keeps the soft delete. Channel deletion
(`soft_delete_discovery_events`) retires the live heads without a
replacement and still soft-deletes them.
This PR has no migration and no schema change.
## Why this is safe
- **Readers:** relay reads of these kinds filter on `deleted_at IS
NULL`, so a retired head was already invisible. One reader includes
soft-deleted rows: the admin event preview (`get_event_preview`). It
will now report a superseded roster id as absent instead of deleted. A
moderation report against an old version of a channel's metadata (for
example, a name it had before a rename) will show no target content. An
operator can no longer look up an old roster or membership list by id to
audit past membership. `docs/admin/README.md` now documents this for
`GET /api/admin/v1/events/{id}`.
- **Operator repair:** when `buzz-admin`'s group-state reconcile
overwrites a 39000–39002 head, the old row is gone, so an operator can
no longer restore it with `UPDATE … SET deleted_at = NULL`. The relay
rebuilds these lists from `channels` and `channel_members`, so no source
data is lost.
- **Replays:** while the coordinate has a live head, a replay of a
deleted head's id is still rejected, because its `created_at` does not
beat the live head's. With no live head (after channel deletion, for
example), the deleted row no longer makes the replay a duplicate. Only
the relay can submit these events: ingest requires the event's signer to
be the authenticated pubkey, 13534 is relay-only, and the relay's
writers sign a new event on every attempt. The existing tests for
soft-deleted replays seed their own rows and do not change.
- **13534 id uniqueness:** the writer still takes `max(created_at)` over
every stored list. The live head is always the newest, so the next
list's `created_at` still moves past every earlier one.
- **13535 strict stamps (NIP-IA, #9476):** each new archived list is
stamped past the live head, which the writer reads behind the
replacement lock. It never reads retired rows, so deleting them does not
change the next `created_at`.
- **Database objects:** no foreign key references `events`, and none of
these kinds is a push kind. The DELETE runs in the same admitted
community write transaction as the old UPDATE. The only trigger left on
`events` is the BEFORE INSERT kind 39002 roster guard
(`guard_channel_roster_snapshot`), and a DELETE does not fire it.
- **Rolling deploy (docs/database.md Rule 7):** old pods keep
soft-deleting and new pods delete. Both leave exactly one live head per
coordinate, under the same locks.
## Follow-up
Rows that are already soft-deleted stay. Rule 3 does not allow a
migration to delete them. A separate PR will add a
`scripts/maintenance/` repair script: bounded batches, the
community-deletion lock, and a validation query. An operator runs it
after this change is fully rolled out.
Not in this PR: the relay-signed NIP-DV DM visibility snapshot (kind
30622, `publish_dm_visibility_snapshot`) is written on the NIP-33 path
and still soft-deletes its superseded heads. We will measure its share
of `events` growth before we change it.
## QA focus
- **Each roster write keeps exactly one stored row.** Create a channel,
then add and remove members, change roles, and edit the metadata. For
each of 39000, 39001, and 39002, the channel must have exactly one
`events` row (live), not one live row plus retired ones. Do the same for
13534 (relay membership add, remove, and role change) and 13535 (`agents
archive` and unarchive).
- **Other kinds still soft-delete.** Replace a kind 0 profile or kind 3
contact list. The old row must stay, with `deleted_at` set.
- **Mention rows.** After a 39002 or 13535 replacement, `event_mentions`
has no rows for the deleted head's id.
- **Admin event preview.** Opening the id of a replaced roster now shows
the event as absent instead of deleted. Check that this is acceptable in
the admin UI, including a report filed against a channel's metadata
before a rename.
- **13535 `since` cache.** Archive and unarchive several times,
including at the same time. Each new list has a `created_at` later than
the one before. A mobile client that asks `since` its list's
`created_at` + 1 gets the newer list.
- **Client 13535 is rejected.** Publishing a kind 13535 signed by a user
key returns `restricted: relay-only kind`. Archive and unarchive (kinds
9035 and 9036) still work, and the relay still publishes its own 13535.
- **Channel deletion.** Deleting a channel still soft-deletes its live
39000–39002 heads. This path is unchanged.
- **Mixed-version rollout.** With an old and a new relay on one
database, each coordinate keeps exactly one live head. Rows that old
pods soft-deleted stay until the follow-up script runs.
- **Existing soft-deleted rows are not touched.** The disk-space gain
shows only in growth after deploy. The follow-up script cleans up the
backlog.
## Tests
- `only_relay_owned_lists_hard_delete_their_superseded_heads`: checks
the kind set, including the neighbours 13533, 13536, 38999, and 39003,
and negative kinds.
- `superseded_heads_drop_their_mention_rows` (Postgres) now expects the
old head to be gone for the 39002 member snapshot, 13535 (global), and
39000 (in a channel). A kind 3 contact list on the same addressable path
is the control: it must stay soft-deleted.
- `replacement_channel_predicate_is_an_index_condition` (Postgres) now
builds its statements with `replacement_sql`, the same function
production uses, for all 4 scope and retire-mode combinations. Before,
it checked hand-copied SQL. It checks that each `DELETE` seeks by
`channel_id` on every populated partition, as the `UPDATE` does.
- The 39002 and 13534 writers take their statements from
`replacement_sql` and `hard_deletes_superseded`, so the index-condition
test covers each statement production runs.
- `nip_ia_archived_list_is_relay_only` (buzz-core): 13535 is relay-only,
and the 9035 and 9036 requests are not.
- `test_client_submitted_nip_ia_archive_snapshots_are_rejected`
(buzz-test-client e2e, against a running relay): a client-signed 13535
is rejected with `restricted: relay-only kind` over both WebSocket and
HTTP. It shares a helper with the existing 13534 test. Against a relay
built without the 13535 gate, it fails at the WebSocket assertion. The
Relay E2E step in `.github/workflows/_ci-relay.yml` now selects it, next
to the 13534 test.
- `late_owner_link_closes_ownerless_agent_sockets_on_owner_revoke`
(buzz-relay, Postgres) copies selected tables into a private schema. The
13534 writer's supersede now also deletes the old list's
`event_mentions` rows, so the fixture copies `event_mentions` too.
- `every_membership_write_commits_its_list` (Postgres): after each
membership writer runs, the community stores exactly one kind 13534 row.
- `concurrent_archival_publishers_stamp_strictly_increasing_snapshots`
(buzz-relay, Postgres, from #9476) counted the 16 stored kind 13535
rows, superseded ones included. It now pins the head an hour ahead and
asserts that the coordinate stores exactly one row, at the pinned
`created_at` + 16 s. That holds only if each of the 16 publishers stored
exactly one snapshot, one second past the head it replaced. A
same-second replacement leaves the row short of + 16 s, and a publisher
that runs out of attempts still fails its `expect`.
- `a_publisher_that_read_before_an_edit_cannot_replace_it` (buzz-relay,
Postgres) counted retired kind 39000 rows to prove that each publisher
stores a new second. It now asserts that the coordinate stores exactly
one row, at the pinned `created_at` + 2 s. The mutation it guards
against (taking the live `created_at` before the lock) leaves the head
at + 1 s, so the test still catches it.
Commands run:
- `cargo clippy -p buzz-core -p buzz-db -p buzz-relay --all-targets --
-D warnings`
- `cargo test -p buzz-core --lib`
- `cargo nextest run -p buzz-relay --lib`
- `cargo test -p buzz-test-client --test e2e_relay -- --ignored` for the
13534 and 13535 rejection tests, against a local relay built from this
branch
- `cargo test -p buzz-db --lib`
- `cargo test -p buzz-db --test observability_source`
- `scripts/postgres-test-run.sh -p buzz-db -p buzz-relay --lib --tests`
(the CI PostgreSQL lane, run locally)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Signed-off-by: Ian Oberst <ioberst@block.xyz>
Co-authored-by: Ian Oberst <ioberst@block.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
8b6bc9beb5 |
Add community-scoped user and agent profile cleanup (#9580)
## Summary
Content, account and media cleanup leave profile records behind. Add
`buzz-admin user-deletions profile-batches` to preview or delete those
records in one community. Preview is the default; explicit `--delete`
applies bounded, retryable transactions.
Every run and retry discovers the human’s current direct agents in that
community. Ownership elsewhere cannot authorize deletion here. If Alice
owns an agent in A but Bob owns it in B, deleting Alice in B preserves
that agent. Each write batch locks and rechecks ownership. All profile
data is removed before identity rows, so an interrupted run resumes
without saved agent keys. The command no longer accepts
`--agent-pubkey`.
The handler removes profile/configuration events and projections,
rebuilds shared archive snapshots with valid signatures, and finally
removes identity rows. Repository announcements/state (30617/30618) and
name mappings remain intact without blocking identity removal; other
authored content still requires prior cleanup. Unresolved dependencies,
changed sources, untrusted signers or excessive plans stop deletion.
This includes historical `replaced-by` references in archive requests
and deltas, even after unarchive removes the current archive row. See
[operator instructions and verification steps](docs/profile-cleanup.md).
Writers must be stopped. Coordinator integration, online admission
fencing, media objects, client caches and final account-erasure
verification remain separate. The command always reports
`account_erasure_complete: false`.
### Related issue
Fixes #9576. Continues the standalone handler pattern from #9363
(content) and #9364 (account). This is an independent PR against main.
### Testing
The latest correction adds a PostgreSQL regression that runs content
cleanup followed by profile preview/delete/retry for human and agent
repository owners. It checks unchanged repository events, mentions, name
mappings and other-community data, and verifies ordinary content still
blocks profile deletion. The merge of main brings in `buzz-deletion
--lib` coverage in the CI unit lane and its fallback, covering the
preview-default parser test without duplicate runs. Account, content,
media and profile command dispatch are all preserved. The
archive-history documentation also now distinguishes planning errors
from printed blockers.
The latest main merge includes the shared dependency-policy correction
from #9609 and the content cleanup lock fix from #9615. On `54bd50299`,
PostgreSQL CI passed 1647 tests and failed 18 because content cleanup
still called the retired SQL lock-key function; this also blocked the
new content→profile regression. The merged upstream fix uses the
existing Rust-built key for both the cleanup lock and the test blocker.
Local test suites and hooks remain skipped at the owner’s request. CI
and review of the updated head are pending. The results below apply to
earlier revisions.
At `92aa9c216`, exercised the rebuilt `buzz-admin` against signed
archive/unarchive events stored in disposable PostgreSQL:
- For kinds 9035 and 8002, test a historical `replaced-by` reference to
the human and then to their owned agent after unarchive.
- Run `profile-batches --pubkey <human> --community <A> --relay-pubkey
<relay>` in preview and `--delete` modes. Both refuse the unresolved
reference; full table dumps remain unchanged.
- Keep that history only in community B. Cleanup in A succeeds,
preserves B, and selects zero work on retry.
- Delete the archive subject in B. Its history is removed while the
replacement identities remain intact.
All four scenarios passed. These are signed database fixtures exercised
through the real CLI; they do not claim live relay admission. The
correction also merges main and preserves content, media and profile
command dispatch.
The initial full database run passed 880/881 tests: the new request
fixture lost its required self-`p` tag during signing. Commit
`ff6689386` preserves that tag; all ten profile regressions now pass.
Further local checks and pre-push hooks were skipped at the owner’s
explicit request. The full corrected database suite has not been rerun;
GitHub CI will validate the new head. At `ff6689386`, the production
code matched the CLI-tested revision; the repository-retention
correction above is newer.
Previous ownership validation follows:
At `090d2a1cf`, exercised the rebuilt `buzz-admin` binary against a
disposable PostgreSQL fixture:
- Run `user-deletions profile-batches --pubkey <human> --community <A>`:
preview left table exports unchanged and selected four profile/identity
mutations.
- Repeat with `--delete --batch-size 2`: all four mutations committed;
retry selected zero work.
- Use the same human and agent keys in another community, with the agent
owned by someone else: only the human was selected, and the agent
remained intact.
This fixture uses placeholder profile signatures and validates
database/CLI behavior. It does not claim live signed-event admission.
The earlier live relay and Desktop results below cover the previous
revision.
Independent agent review covered the previous ownership correction. A
later review found the historical replacement-reference bug; the
historical-reference correction addresses that finding. Fresh review of
this revision is still required. Human command verification has not been
recorded; it is not claimed by the agent-run checks. Follow the local
verification steps in `docs/profile-cleanup.md`; preview must leave data
unchanged, deletion must preserve other-community records, and retry
must select zero work.
<details>
<summary>Historical validation at
|
||
|
|
051dd2d7aa |
fix(sdk): timestamp channel messages with millisecond offsets (#9548)
Kind-9 messages sent through the SDK or `buzz messages send` omit the `ms` tag, so clients break same-second ties by event ID. Capture one clock reading in the shared message builder and use it for both `created_at` and the canonical 0–999 millisecond offset, including direct and nested replies. Validation: both new regressions failed before the fix; the full CLI suite (691 tests) and SDK suite (335 tests) pass. The SDK test checks that the timestamp is pinned before signing; the CLI test captures and verifies signed HTTP submissions for roots and both reply depths. The built CLI also sent direct and nested replies through a managed signer to a live relay; readback confirmed one canonical `ms` tag and correct thread tags on both. Client ordering and human testing remain pending; keep this PR draft. To test manually, run `cargo build -p buzz-cli`, then send several kind-9 messages with `target/debug/buzz messages send --channel <channel> --content <text>` and direct/nested replies using `--reply-to <event-id>`. Inspect their raw events: each should carry exactly one canonical `ms` value, and a client that honors `ms` should display same-second sends in timestamp order. Related: #9541 updates mobile display ordering to consume these offsets. No duplicate producer fix found in the open PR/issue search. Repository-wide validation: `just ci` passed Rust/Tauri Clippy and formatting, then failed mobile analysis at `mobile/test/features/search/search_channels_journey_test.dart:933`: `_RenamingSession.subscribeWithStatus` omits the base method's `resumeSince` parameter. Mobile files are unchanged from the base commit. This unrelated failure remains outside this fix. The first push hook run failed the existing WebSocket throttle test `a_throttled_sign_in_reconnects_with_fresh_evidence` (connection reset during sign-in); a subsequent full CLI rerun and the complete normal push-hook retry passed without source changes. The test uses a kind-20001 event and does not call the changed builder. All required push hooks passed. Signed-off-by: Rocket <0c41329ade659e01801116549bc617351689892a382bc864a1186dc9191293a7@buzz.block.builderlab.xyz> Co-authored-by: Rocket <0c41329ade659e01801116549bc617351689892a382bc864a1186dc9191293a7@buzz.block.builderlab.xyz> |
||
|
|
3bd121bc15 |
Check product_feedback's community in the writing transaction (#9608)
## Summary Third app-side step of retiring the database foreign keys (after #9399 and #9404). After this, every reference the drop migrations will remove is checked in application code. - **`product_feedback -> communities`:** `product_feedback::insert` now runs in a transaction. It locks the community row `FOR KEY SHARE` and returns `NotFound` when the row is missing. This is the same guarantee the foreign key gives. Any lifecycle state still qualifies. `docs/database.md` says provenance-only tables stay writable while their community is being deleted, and the purge clears their provenance. - **Reader tolerance:** `ProductFeedbackRecord.community_id` is now `Option<Uuid>`. The purge sets `community_id = NULL`, and `list` (used by `buzz-admin list-product-feedback`) failed to decode those rows. The JSON output shows `null` for them. - **One home for reference checks:** `require_workflow` and `require_workflow_run` move from `store/workflow.rs` into `store/reference_check.rs`. The workflow owner and channel checks now reuse `require_user` and `require_optional_channel`, so two duplicate helpers are gone. A new `require_community` joins them. - **Stale comments:** comments that justified behavior by the foreign keys now say what holds both before and after the drop. Touched: the purge order (`deletion.rs`), `command_executor.rs`'s `ensure_user`, the `set_agent_owner` doc, the NIP-43 snapshot lock note (`relay_members.rs`), `attach_scheduled_workflow_run`, and one workflow deletion test. ## Writers and readers checked (RPR #2) `product_feedback.community_id` writers: - `store/product_feedback.rs` `insert`: the only insert. It is now checked. - `store/deletion.rs` `purge_postgres`: sets the column to `NULL`. No check is needed. - `store/relay_admin_actions.rs` status update: does not touch `community_id`. Readers: - `product_feedback::list`: fixed to accept `NULL`. - `store/admin_moderation.rs` inbox queries: already `LEFT JOIN` and accept `NULL`. ## Tests All three tests drop `product_feedback -> communities` in the per-test database first, so a pass proves the application check and not the constraint. - `insert_rejects_missing_community_without_foreign_key`: a community that never existed gets `NotFound` and no row. A fenced community still accepts feedback. An active one accepts it, and a replay returns the same row. - `insert_key_share_locks_community_without_foreign_key`: an insert waits while another transaction holds the community `FOR UPDATE`, then proceeds. - `list_returns_rows_with_cleared_provenance`: a row with `community_id = NULL` is listed with `community_id: None`. ## Not in this PR - The foreign key drop migrations. They come after this PR is deployed (`docs/database.md` expand/contract). - Nothing in the database stops `DELETE FROM communities` on an active community once the community foreign keys are gone. The tombstone trigger rejects it only for inactive communities. Production never hard-deletes communities. This is decided with the drop migrations, since a trigger change conflicts with the no-new-triggers rule. ## What got simpler All in-transaction reference checks now live in one module. Two duplicate helpers were removed. `store/workflow.rs` loses about 80 lines. buzz-review-completed 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Luke Tornquist <tornquist@squareup.com> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Tom Brow <tomb@squareup.com> |
||
|
|
0a05330740 |
buzz-db: stop calling the dropped lock-key function in SQL (#9615)
## Summary Main's user content cleanup still calls the SQL function `community_deletion_lock_key`. Migration `0094` (#9598) drops it. On any database at `0094`, every user-deletion content batch fails with `42883 function community_deletion_lock_key(uuid) does not exist`. #9363 added this caller after #9396 moved the key to Rust. This PR binds the Rust-built key with `hashtextextended($1, 0)`, as every other caller does. - `content_batches/execute.rs`: the batch's exclusive advisory lock uses the Rust key. - `content_batches/safety_postgres_tests.rs`: the test blocker takes the same lock the same way. - `docs/trigger-retirement-deployment.md`: builds from #9363 up to this PR are not valid stops before `0094`. Rebased onto main `e894d75d`. The renumber and the `update_channel` test-call fixes this PR first carried are already on main through #9616, so they are gone from this PR. Deployed relays are unaffected: the deployed build predates #9363. ## Tests The 17 `user_deletion::content_batches` PostgreSQL tests fail on main at `0094` with the error above. This PR makes them pass. ## What got simpler One fewer SQL-side copy of the lock key. Every caller now builds the key in Rust. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
8fb0de8d53 |
Clean up account records and refresh member lists (#9364)
## Summary Add bounded, resumable cleanup for a user’s account records and their current direct agents in each selected community. Preview prints the proposed changes without writing; deletion uses the same selectors through the command and workflow handler. Each run and retry discovers agent ownership again. An agent owned by Alice in one community and Bob in another is cleaned only in Alice’s community. Ownership changes stop the current run, and ownership rows remain available for retries and later handlers. Membership removal rebuilds and signs the current channel lists and community roster in the same transaction as each removal. A failed roster write rolls back that membership removal. The command requires the existing relay signing key when channel or community memberships are present, including users with no channel memberships. Preview does not require a key. The relay, account cleanup and admin reconciliation share the kind 39001/39002 tag builders in `buzz-db`. They preserve the existing identity tags, roster order and role positions. Regular unit-test runs now include `buzz-deletion` through both nextest and the Cargo fallback. **Channel ownership policy:** deletion may remove the last channel owner, including when the human and their agents are all owners. The channel, messages and surviving members remain. A surviving admin can manage the channel and grant ownership. If no owner or admin remains, members can continue normal use, but management recovery requires operator intervention on request. Cleanup does not require a channel ownership handoff or assign a replacement owner. The separate community-owner restriction remains. The content handler now on main advances to account cleanup before the remaining agent stage. Content and account workflow progress goes to stderr so stdout remains one JSON inspection document. The direct account command retains NDJSON stdout. Nullable attribution updates use explicit table and SET clauses so the source-policy guard can inspect them. The handler covers credentials, memberships, read progress, supported personal events and their copies, feedback, and explicit global listener/database-role cleanup. It retains shared records and historical signed lists. Scope files select the human and communities; saved agent keys do not authorize deletion. This remains an offline operator feature: stop relay and external writers before deletion. It does not revoke already-connected sessions. Coordinator integration, remaining handlers and final erasure verification are separate; results always report `account_erasure_complete: false`. The real account workflow still stops at an unimplemented successor. ### Related issue Replaces the account scope of #9354 and #9355 with one focused PR. Those earlier PRs remain intact for reference. Agent cleanup belongs within the business handlers; this change does not integrate the historical standalone agent stage in #8959. ### Testing Exercised the real preview and delete commands in an isolated local relay/database with Alice disconnected and Bob’s desktop app open. Preview left the normalized database dump unchanged. Deletion checks covered all 101 tables and all 30 affected channels; 168 newly signed list events verified. Bob refreshed the member dialog and saw Bob, B1 and Carol, then successfully sent and read a message. A1’s membership in the community where Bob owns it remained intact. The live CLI and desktop evidence above predates the latest follow-up. Independent end-to-end checks at `d45759df2` also verified unchanged preview data, signed channel/community lists after deletion, signing-key preflight, and workflow JSON stdout. The shared-builder follow-up was source-reviewed and formatted; local builds, tests and commit/push hooks were skipped at the author’s request. Validation of the new revision and a repeat of the signed-list end-to-end check are pending. Human testing remains pending. For human verification, use an isolated database and its relay signing key. Preview a community-only member, confirm no writes, then delete and verify the current kind 13534 roster omits them. Run an approved account-stage fixture with `user-deletions run <id> --delete --next-step`; the entire stdout must parse as one JSON document, with batch progress on stderr. Generated with Codex --------- Signed-off-by: Ravneet Arora <rarora@squareup.com> Signed-off-by: soup <757a365d4ee72aedf003a39cd856b16b49a3b940a42fe00402b8f80fbc40e730@buzz.block.builderlab.xyz> Co-authored-by: soup <757a365d4ee72aedf003a39cd856b16b49a3b940a42fe00402b8f80fbc40e730@buzz.block.builderlab.xyz> Co-authored-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz> |
||
|
|
e894d75d26 |
buzz-db: fix main (renumber the function drop to 0094, update_channel test call) (#9616)
## Summary Main has two migrations numbered `0093`: - `0093_push_gateway_installation_platform.sql` from #9560 - `0093_drop_plain_sql_functions.sql` from #9598 The file names differ, so GitHub showed no conflict between the PRs. sqlx applies the first version-93 migration and then rejects the second as a changed migration 93. Every migrate run on main fails, including relay startup with auto-migration on. This PR moves #9598's migration to `0094`: - `git mv migrations/0093_drop_plain_sql_functions.sql migrations/0094_drop_plain_sql_functions.sql`. The SQL is unchanged. - `embedded_migrator_contains_consolidated_initial_schema` now expects 94 migrations, with the function drop at version 94. - The Postgres test is renamed to `migration_0094_drops_plain_sql_functions`. It finds the migration by description, so its logic is unchanged. - `docs/trigger-retirement-deployment.md` now names `0094`. #9560's `0093` keeps its number. It reached main first and may already be applied on deployments that auto-migrate. ## Second break on main: `update_channel` call sites Main's buzz-db lib tests also stopped compiling. #9581 added a `sender` argument to `update_channel`, and #8320's cross-community test (`deletion.rs`) landed in parallel with the old three-argument call. This PR passes the channel creator as the sender. The test only renames an open channel, so the private-to-open rule does not apply. ## Deployments No deployment has applied #9598's `0093`: no image built from main after #9598 has rolled out yet. A database that applied #9560's `0093` applies `0094` next. Do not promote any image built from `4e8f8365` (the #9598 merge) or later until this PR merges. ## What got simpler Nothing. This is a renumber and a test call fix only. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
f158fdd9a1 |
feat(relay): name the agent whose add policy refuses a DM (#9601)
## Problem When an agent's add policy refuses a DM open or add (from #9125), the refusal says only that an agent refused. The person can't tell which agent blocked it, so they don't know whose owner to ask. ## Change The DM refusal now ends with `(agent <hex pubkey>)` for the first agent refused, in the order the request named them. For example: `forbidden: policy:owner_only — only the agent owner can add this agent (agent 3f9a…)` The prefix is unchanged, so existing clients that match on `policy:owner_only` or `policy:nobody` keep working. Desktop and mobile follow-ups will show the agent's name. ## Tests - `adding_an_agent_follows_its_add_policy` asserts the full refusal including the agent. - `opening_with_several_agents_follows_their_add_policy` adds a second refusing agent and checks the first one named is reported. - DM Postgres tests: 297/297 passed. Clippy is clean. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com> Co-authored-by: Carl <c217fe6b9d958f41c3a5e030dccc7f626775a923089cb6491305eade75ea1f1b@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
4e8f836576 |
buzz-db: drop the community_deletion_lock_key and profile_name_fields functions (contract) (#9598)
## Summary Phase 2 of retiring the two remaining plain SQL functions. Phase 1 moved their work into the relay: - #9396 builds the community deletion lock key in Rust (`deletion::community_deletion_lock_key`, locked with `hashtextextended($1, 0)`). - #9397 reads profile names with inline SQL (`PROFILE_NAME_FIELDS` in `buzz-search`). No relay at or after #9397's merge (`279a31da`) calls either function. This PR drops them: - **Migration 0093** runs `DROP FUNCTION community_deletion_lock_key(UUID)` and `DROP FUNCTION profile_name_fields(TEXT)` under a 5s `lock_timeout`, with no `IF EXISTS` and no `CASCADE`. If anything still depends on a function, the migration fails instead. Migrations 0029 and 0064 stay frozen. No database function calls either one any more: 0090 dropped the fence functions, which were the only SQL callers of the lock key. - **Desired state:** removes both `schema/functions/` files and their `schema.sql` includes. Both boot paths stay catalog-equivalent (`admin_schema_parity_between_desired_state_and_migrations`). - **Tests:** - New `migration_0093_drops_plain_sql_functions`. It migrates to 0092, checks that both functions exist and that serving and deletion catalog validation pass, then runs 0093 and checks that both functions are gone and that validation still passes. This covers new code on either side of the drop. - The migration listing test pins 0093's statements and that it has no `CASCADE`. - `desired_state_catalog_has_no_universal_fence_and_still_boots` now asserts that both functions are absent. - Replaces the Rust-vs-SQL lock key parity test with `community_deletion_lock_key_bytes_are_fixed`, a unit test that maps fixed UUIDs (nil, max, and one with hex letters) to their exact keys. Older replicas and the repair-script key in `docs/database.md` build the same string, so a changed prefix or UUID format must fail a test. - Removes two relay test-schema wrappers (`bridge.rs`, `ingest.rs`) that forwarded `community_deletion_lock_key` to `public`. Writers no longer call it, and the wrapper's `CREATE FUNCTION` would fail once the function is gone. - **Docs:** `docs/trigger-retirement-deployment.md` gets a `0093` section with the required stop. ## Deploy gate **Required stop:** any relay build at or after `279a31da` (#9397's merge, which follows #9396). `relay-v0.3.0` does not contain it. A relay older than that which still serves after 0093 fails every write and deletion that takes the community deletion lock, with `42883 community_deletion_lock_key(uuid) does not exist`, and its profile name search fails with `42883 profile_name_fields(text) does not exist`. 0093 takes no table locks and needs no cleanup. Migration number: #8696 and #9398 also propose `0093`. Whichever lands second renumbers. ## Review-Proven Rules - **RPR #2 (every path):** I checked every reference on `main` and at the stop build `279a31da`. At both, only test code reads either function: no boot, readiness, catalog or runtime query depends on them. Serving and deletion catalog validation pass before and after 0093, in the new test. - **RPR #3 (falsifiable):** removing the `profile_name_fields` drop from 0093 turns `migration_0093_drops_plain_sql_functions` red. - **RPR #3 (lock key bytes):** a changed prefix, `.simple()` UUID formatting, or uppercase formatting each turns `community_deletion_lock_key_bytes_are_fixed` red. ## What got simpler Two database functions, their desired-state files, a cross-language parity test and two test-only SQL wrappers are gone. After this PR, the only functions left in `schema/functions/` are trigger functions. ## Validation Blox gate at `95ac71c8`: - `cargo fmt --all --check`, and `cargo clippy -p buzz-db -p buzz-relay --all-targets -D warnings`. - `buzz-db --lib` unit tests: 216/216, including the migration listing test. - `buzz-db` Postgres tests (`migration::`, `deletion::`, `nip_fi_binding::` postgres_tests): 130/130. These include `migration_0093_drops_plain_sql_functions`, `admin_schema_parity_between_desired_state_and_migrations` and `deletion_surface_parity_between_migration_0029_and_schema_sql`. - `buzz-search` `profile_names*` Postgres tests: 4/4, on a fully migrated database where `profile_name_fields` no longer exists. - The two relay tests whose test-schema wrapper this PR removes: 2/2. - Must-fail check: with the `profile_name_fields` drop removed from 0093, `migration_0093_drops_plain_sql_functions` fails. Second Blox gate at `e1b5513a` (the lock key vector test): - `cargo fmt --all --check`, and `cargo clippy -p buzz-db --all-targets -D warnings`. - `buzz-db --lib` unit tests: 217/217. - Must-fail checks: a changed prefix, `.simple()` and uppercase UUID formatting each fail `community_deletion_lock_key_bytes_are_fixed`. The first gate run found that `deletion_surface_parity_between_migration_0029_and_schema_sql` still expected `community_deletion_lock_key` in `schema.sql`. The second commit fixes that. 🤖 Generated with [Claude Code](https://claude.com/claude-code) buzz-review-completed --------- Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
6b4a398829 |
feat(push-gateway): enroll Android installations and send FCM wakes (#9560)
## What and why Ticket 2 of the Android push plan ([design PR #9555](https://github.com/block/buzz/pull/9555)). The gateway now enrolls Android installations and wakes them through FCM, next to the existing iOS path. Builds on [#9557](https://github.com/block/buzz/pull/9557) (platform-neutral `/v1/deliveries` route), now merged. - **Platform.** The enrollment request has no platform field. The gateway derives it from which attestation is present (App Attest object or Android attestation chain) and records it in a new `push_gateway_installations.platform` column (`ios` or `android`). It lives only in gateway state; the relay never sees it. - **Android enrollment transcript.** Key Attestation fixes the challenge at key generation, so the client signs nothing at enrollment and sends no `key_id`. The attestation challenge must equal SHA-256 of a canonical JSON transcript under domain `buzz.push.enroll.android.v1` with `v`, `audience`, `challenge_id`, `challenge`, `endpoint`, `endpoint_epoch` and `expires_at`. The gateway derives the key id as SHA-256 of the attested 65-byte uncompressed P-256 key. A request whose `key_id` presence doesn't match its platform gets 400. The iOS transcript (`buzz.push.enroll.v1`) is unchanged. - **Signed calls.** iOS keeps App Attest assertions. After enrollment, an Android installation signs every call (delegate, revoke delegation, rotate endpoint, revoke installation) with its attested Keystore key: ECDSA P-256, DER, over the same transcript bytes iOS signs. High-S signatures are accepted since Keystore does not normalize. There is no counter; the single-use challenge inside the transcript is the replay protection. - **FCM sender.** HTTP v1, high priority, data-only, compiled-in payload (no relay-supplied bytes), one constant collapse key, TTL from the delivery expiry. OAuth access tokens come from the service account key (RS256 JWT bearer). Outcomes map onto the existing delivery outcome classes and metrics (`push_gateway_fcm_*`). - **Token refresh.** A cached token keeps serving until it expires. Once it is due for refresh, one background task fetches a new one, so a wake never waits on a refresh while a valid token exists. A failed fetch keeps the current token and backs off 5 s before the next attempt. Only a cold cache (no unexpired token) makes a wake wait on the token request, single-flighted. A 401 discards the cached token only if it is still the one FCM refused, so a late 401 can't drop a newer token. - **Retries.** 429 and `QUOTA_EXCEEDED` retry after at least 60 s (FCM's hint if longer). 500, 502, 503 and 504 retry. - **Attestation seam.** Android Key Attestation verification sits behind a trait. Tests use a test-only verifier compiled under `cfg(test)`, so production configuration cannot select it. The production verifier fails closed: a gateway configured for Android starts but rejects every Android enrollment until ticket 3. - **Migration.** Expand-only `ADD COLUMN platform TEXT NOT NULL DEFAULT 'ios' CHECK (...)`: the deployed gateway's inserts stay valid and existing rows become iOS. `SET LOCAL lock_timeout` (5 s) and `statement_timeout` (30 s) bound the table lock wait and the CHECK validation scan. No triggers, functions, foreign keys or backfills. Mirrored as gateway `0007` and relay `0093` plus `schema/tables/public`, per docs/database.md. ## Configuration All four are optional and must be supplied together (a partial set fails startup). Documented in `docs/push-gateway-deployment.md` and `.env.example` with example values only. - `BUZZ_PUSH_ANDROID_PACKAGE_NAME` - `BUZZ_PUSH_ANDROID_SIGNING_CERT_DIGESTS` - `BUZZ_PUSH_FCM_PROJECT_ID` - `BUZZ_PUSH_FCM_SERVICE_ACCOUNT_PATH` ## Tests - `cargo test -p buzz-push-gateway` (92 passed, 18 ignored; 94 passed with `personal-dev-app-attest`; iOS rows unchanged), `cargo fmt --check`, `cargo clippy -p buzz-push-gateway -p buzz-db --all-targets -- -D warnings`. - New HTTP tests with a fake FCM sender: Android enroll, delegate, deliver, rotate endpoint and revoke; signed-call rows for wrong key, altered transcript and reused challenge; platform derivation and bad attestations. - Postgres (ignored, run locally): gateway migration test (existing and old-gateway inserts become `ios`, bad value rejected); relay `admin_schema_parity_between_desired_state_and_migrations` now covers `push_gateway_installations` columns, indexes and constraints; the `runtime::migration::postgres_tests` set passes single-threaded. - Break check: making signature verification always succeed turned two tests red (the signed-call rejection rows and the signature unit test); restored. - Token cache tests against a local fake token endpoint with a controlled clock: a due refresh keeps serving the valid token even when it fails; a late 401 does not discard a refreshed token; a queued background refresh honors a foreground failure's backoff. The FCM response table covers 429 with and without an error body, and 502/504 HTML pages. - Android enrollment rows: `key_id` present on Android (400), wrong transcript binding, a 65-byte non-point key, an over-long chain, and exact replay. - Break checks for every new guard (no background refresh, blocking while due, failure dropping the token, unconditional 401 clear, no quota floor, no 502/504 retry, the queued-refresh backoff check, Android requiring `key_id`, skipping the P-256 point check): each turned at least one test red; restored. ## Not here (ticket 3) Real Key Attestation verification (Google roots, revocation list, boot state, boot-key list, app identity). Per-key rate limiting is also left for ticket 3, since it did not fall out of this change. The Helm chart does not pass the Android settings yet. --------- Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> |
||
|
|
50cfc54337 |
Apply the private-to-open rule in update_channel too (#9581)
## Summary - Follow-up to https://github.com/block/buzz/pull/9307, which made the relay refuse to open a private channel that has, or once had, any member other than the sender and the sender's own agents. That rule lived only in the channel metadata edit path (kind:9002). The store's other channel-settings function, `update_channel`, could still open such a channel. - Now both paths apply the same rule, because it runs in the one function that writes channel settings for both. `update_channel` takes the authenticated sender so it can decide the rule. Today only tests call `update_channel`, so nothing user-visible changes; the gap is closed before any real caller arrives. - The user-deletion executor doc now says what the rule needs from a purge: if a purge keeps any of a user's messages in a channel, it must also keep that user's membership row there, marked removed. The relay finds former members only through those rows, so dropping the row would let the channel be opened and its history, those messages included, be made public. ## Details - The check moved out of `apply_channel_metadata_event` into `update_channel_on`, which both paths call. It still runs under the membership lock that a visibility change takes, so members cannot be added between the check and the commit. - One ordering change: a single kind:9002 that opens a private channel with other members, archives it and sets `auto_join` to true now gets the `auto_join` refusal instead of the private-to-open one, because the `auto_join` check now runs first. Both refuse, and nothing is stored either way. - This PR also carries doc-comment wording that was reviewed on https://github.com/block/buzz/pull/9307 but not merged with it: the comments now give the reason, that opening publishes the existing history, so removed members count. - Every call site of `update_channel` is a test, and each now passes the channel owner as sender. ### Related issue Follow-up to https://github.com/block/buzz/pull/9307 (review notes on its store gap and on purge). ### Testing - New Postgres test `update_channel_refuses_opening_a_private_channel_with_other_members`: opening fails for both the owner and the other member as sender, while the other member is current and after they are removed, and the channel stays private. A channel that holds only the owner opens. - The existing kind:9002 test `private_to_open_needs_no_other_members` still passes. Both tests fail when the check is removed. buzz-review-completed 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Logan Johnson <loganj@squareup.com> Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
a8f55e637a |
Add real content cleanup for users and agents (#9363)
## Summary Add one shared content-cleanup handler for a user and their agents in a specified community. Preview is the default; deletion commits bounded batches and preserves other people's replies and reactions. Agent selection requires ownership by this user in the target community. Ownership elsewhere is insufficient. The start record reports missing or conflicting ownership, and every batch rechecks the selected agents before deleting anything. ### Reply preservation and live writes Keep erased placeholders for messages needed by surviving reply chains or reactions. Plain links and quotes may point to a deleted message; their signed source messages stay unchanged. Nested reply ancestry uses the existing parent/root indexes. No new permanent index or schema migration is added. Replies without thread metadata use the existing tags GIN index to search for each selected message ID in lowercase and uppercase. The shared marker parser checks which matches are actual replies. Mixed-case references without thread metadata may be missed; metadata-backed replies use binary IDs and remain covered. Planning and hard-delete rechecks each run the probes in one SQL statement with a one-second timeout and a 10,000-match limit. A reply matching several probes counts several times. Exceeding either bound aborts cleanup. This avoids the broad search through unrelated replies; production-scale performance has not been measured. Each batch revalidates its work under the community lock. Transaction-local timeouts apply before locking, including after reconnect. Planned output is written before locking and receipts after commit. A changed row, owner, or surviving reply aborts the batch; retry replans remaining work. Normal reply insertion retains the added indexed parent-existence check. This changes the live write path and prevents saving a reply whose parent disappeared while the writer waited. Erased messages appear unavailable in moderation lookups instead of carrying an empty author key. ### Included content Supported authored events and owned reaction, subscription and notification records are included. Signer-owned personas (30175), team definitions/catalogs (30176/30178), emoji sets/entries (30030/30180), and project groupings (30621) include shared publications and stored revisions. Deleting a project grouping leaves member repositories, their announcements/state and name mappings intact. ### Testing Local runtime tests and hooks are skipped at the owner's request. Source review, Rust formatting and diff checks were completed. The updated revision requires CI validation; earlier test runs and index benchmarks do not validate this replacement. Regression cases cover ownership conflicts/transfers, missing thread records, nested ancestry, plain links, late replies, lookup limits, reconnects, blocked output, and unavailable moderation targets. No new manual relay or UI test was run for this revision. Account blocking remains unfinished; these changes do not establish complete online account erasure. ### Scope and compatibility **Deferred to a separate follow-up PR to keep this PR smaller:** the following work will extend **the same content cleanup handler** (`purge_content` / `content-batches`), rather than introduce another handler: - Workflow database definitions, runs, traces, approvals, schedules and copied inputs; some source events are already covered here. - Canvas revision events and current canvas text. - Artifact events, revision records and current heads. - Channel topics and purposes. - Gift-wrapped DMs and additional huddle history that require different attribution rules. - Git issues, PRs, patches, comments/status and required repository metadata, subject to preservation rules. Repositories themselves stay. - Remaining stored workflow, delivery and projection copies outside this PR's current coverage. These categories remain unfinished. Deferring them is not a permanent retention decision or a claim of complete content erasure. The follow-up must settle shared-document and mixed-owner workflow behavior and test surviving content. Profiles and managed-agent identity definitions belong to profile cleanup. Memberships, personal preferences and access belong to account cleanup. Media cleanup was implemented separately in #9365 and is now on main. Deletion requests, approvals, progress/history and replay protection stay. The workflow orders account gating, global media cleanup, then per-community content cleanup. Real requests still stop at the unfinished account gate; demos simulate every stage without deletion. Other unfinished real workflow stages fail explicitly. Existing demo requests saved with `purge_db` must be recreated for `purge_content`. Bulk client notifications remain separate work. Open views may retain cached content and counts until refresh. The existing missing reply-count button after refresh and ordinary UI access when the root is deleted are outside this PR. Replaces the content portion of #9355 and #9332. Related prior handler: #8698. Generated with Codex --------- Signed-off-by: Ravneet Arora <rarora@squareup.com> Co-authored-by: maincourse <37ce551b493d4a998caf030929c47bce0b6a0e43f1178b3a63c4151d7c16b76e@buzz.block.builderlab.xyz> |
||
|
|
c0ce4982fc |
buzz-db: check membership, agent-owner and channel references in app code (#9404)
> Builds on #9399 (its two commits are included here until it merges;
review only the commits after `367d3486`).
## What
This is the second app-side step toward retiring every foreign key,
following `docs/database.md` ("Retiring a trigger, function, or foreign
key"). Each writer below now checks its parent inside the writing
transaction and locks it `FOR KEY SHARE`, the same lock an FK check
takes. The FKs stay in place, so both checks run and agree. A later
contract migration drops them.
The shared helpers are in a new `store/reference_check.rs`:
`require_channel`, `require_optional_channel`, `require_user` and
`require_relay_member`, all community-scoped. A missing parent returns
`DbError::NotFound` and nothing is written.
| FK | Writer | Change |
|---|---|---|
| `join_policy_acceptances → relay_members` | `relay_invite.rs` (both
claim paths), `relay_invite/claim_owner.rs` | One helper locks the
member row, then inserts the acceptance. The existing-member read is now
`FOR KEY SHARE`. |
| `users.agent_owner_pubkey → users` | `user.rs`
`set_agent_owner_with_operation` | Reads the agent row `FOR NO KEY
UPDATE`. A missing agent → `NotFound`; an already-owned agent →
`Ok(false)` without examining the owner; otherwise the owner is checked,
then the UPDATE runs. `NotFound` for a missing owner therefore holds
with or without the self-FK. |
| `channel_members → channels` | `channel_members.rs`
`insert_auto_membership`, `lock_channel_archived_at_in_transaction` |
The auto-add checks the channel. The archive lock now returns
`ChannelNotFound` for a missing row instead of reading as not archived.
A soft-deleted channel still reads `None`. |
| `thread_metadata → channels` | `event.rs`, `thread.rs` | Checks the
channel before writing thread metadata, in the event's own transaction.
|
| `moderation_reports/actions → channels` | `moderation.rs`,
`relay_admin_actions.rs` | Checks a non-null `channel_id` before the
write, after the existing rejection outcomes (not-found,
already-claimed, not-open, replay). |
**Real race closed.** Member removal locks the member row `FOR UPDATE`,
deletes the acceptances, then deletes the member. The acceptance insert
used to follow an unlocked member read, and a membership `INSERT … ON
CONFLICT DO NOTHING` locks nothing when the member already exists. Today
only the FK's implicit `KEY SHARE` stops an orphan acceptance; this
change makes that lock explicit.
**Caller-visible behavior.**
- The huddle join in `audio/handler.rs` maps `ChannelNotFound`, meaning
the channel was purged between the pre-join check and the lock, to
`MembershipLost` before any write.
- `set_agent_owner` has one production caller, `api::write_agent_owner`.
It runs `ensure_user_for_authorization` on both the agent and the owner
first, so its behavior is unchanged.
- `put_members` keeps its existing error.
## Tests
- `store/reference_check_postgres_tests.rs`: 9 tests, one missing-parent
test per writer plus a `KEY SHARE` lock test. Each drops the covered FK
in its per-test DB (`test_support::drop_foreign_keys_between`), so it
proves the app check. The `insert_report` upsert test pins precedence: a
missing channel beats an existing report, and the stored row is
unchanged.
- `relay_members.rs`:
- Two new race tests: a membership claim racing member removal, and an
invite claim racing member removal.
- The existing
`member_removal_waits_for_and_removes_concurrent_acceptance` now runs
against the explicit lock.
- The `wait_for_put_member_behind` query pattern in `api/invites.rs`
tests was updated to the new query text.
- `relay_members.rs`
`invite_claim_conflicting_with_a_member_added_mid_claim_waits_for_removal`:
a `#[cfg(test)]` pause before the membership INSERT
(`relay_invite::test_hook`) lets a member commit mid-claim and a removal
hold it `FOR UPDATE`. The claim must wait, then return `NotFound` with
no acceptance, no orphan, and no invite use.
- `set_agent_owner_rejects_missing_owner_with_and_without_foreign_key`:
asserts `NotFound` and an unchanged owner with the FK installed, then
with it dropped.
Falsification: removing the check at each of the 10 call sites turns its
test red. So does stripping `FOR KEY SHARE` from each helper and from
the invite member read. Swapping the conflict-branch helper for a raw
acceptance insert, or moving the owner check back after the UPDATE, also
turns its test red.
## Validation
Run on a cloud workstation at this tree (
|
||
|
|
ec778bff9a |
buzz-db: enforce five single-table guards in app writers (phase 1) (#8320)
> **Also carries the catalog expand** (`cdc88edd`) for phase 2 (#9398). `validate_serving_catalog`, used at boot and readiness, no longer requires the `communities_deletion_tombstone` trigger, only `community_deletion_lock_key(uuid)`. Without this, a pod would fail boot after `0090` drops the guards. Regression: `migration_schema_single_table_guards_are_optional_for_serving_and_deletion` migrates through `0086`, validates serving, readiness and the deletion lifecycle, drops the five guards, and validates again. No schema change. ## What This is phase 1 of 2 for retiring five single-table guard triggers (BUZZ-318). Their invariants now hold in the application writers. **All five triggers and their functions stay** for mixed-version pods. A later PR drops them. | Trigger / function | App-side enforcement | |---|---| | `trg_channels_community_id_immutable` | **By construction.** Inserts bind the tenant once. No production `UPDATE channels` assigns `community_id`, and `ChannelUpdate` has no community field. A source policy pins this. | | `communities_deletion_tombstone` / `enforce_community_tombstone()` | **One state machine.** `begin_quiescing`, `fence`, `purge_postgres` and `abort` all go through `transition_community`, using a `FOR UPDATE` row snapshot in the caller's transaction (quiesce, fence and abort also hold the community deletion advisory lock; purge does not, and its tombstone transition fails if a concurrent abort won). Allowed transitions: active→quiescing (plus a quiescing retry); quiescing→fenced, which increments the generation; fenced→tombstone at the same generation, with a one-way `deleted_at`; active/quiescing/fenced→active on abort, which also increments the generation. Every transition rejects an already-deleted row. The UPDATE is conditioned on the snapshot's state and generation. `set_community_icon` updates only an active, undeleted row and returns `AccessDenied` otherwise. Archive and unarchive lock an active row, and their UPDATEs also carry `deletion_state = 'active'`, so every non-lifecycle `communities` UPDATE or upsert carries the active predicate (policy-pinned: a non-active row is immutable outside the state machine). No production `DELETE FROM communities` exists, and the policy forbids adding one. Executor GUCs are unchanged. | | `community_deletion_request_retargeting_guard` | **Mostly by construction, plus predicates.** No production UPDATE assigns target identity or provenance (policy-pinned). Both initial inventory freezes (`freeze_inventory`, `complete_owner_preparation`) require `stage = 'submitted' AND blocked_at IS NULL AND inventory_frozen_at IS NULL` in their UPDATE. Every request UPDATE that assigns an inventory column must carry `inventory_frozen_at IS NULL`, and one that assigns `destructive_storage_*` must carry the frozen-or-equal guard (policy-pinned). The destructive-manifest freeze now also refuses a row that is marked frozen but is missing its manifest JSON. | | `community_deletion_approval_removal_guard` | **By construction.** Approvals are insert-only (`approve`, `complete_owner_preparation`). The policy forbids any production UPDATE, `ON CONFLICT … DO UPDATE` upsert or DELETE. | | `community_deletion_manifest_keys_guard` | **One shared check.** Append, pre-freeze clear and verified cleanup each lock the request row and check its stage and freeze status through `guard_manifest_chunk_write`. Chunk content is never updated: the policy rejects every chunk UPDATE or conflict upsert except `mark_manifest_chunk_deleted`, the only writer that stamps `deleted_at`. That stamp must be the function's only chunk write, a plain UPDATE of exactly `SET deleted_at = now()`, with `request_id = $1`, `chunk_no = $2` and `deleted_at IS NULL` as plain conjuncts (no `OR`, no subquery), so it stays one-way. | **The app is stricter than the triggers, not equivalent to them.** `enforce_community_tombstone()` admits any change when the executor GUC matches, before it looks at lifecycle columns, so the transition graph above lives only in `transition_community`. The chunk DELETE trigger also allows cleanup when the parent request is missing or unfrozen, while `guard_manifest_chunk_write` allows only fenced-and-unfrozen or verified cleanup. Every current caller already runs at those stages. Writer inventory: I searched every production writer of these tables and columns across all crates, excluding `#[cfg(test)]`. That covers buzz-db, buzz-deletion, buzz-relay handlers, side effects and operator/admin APIs, and buzz-audit. Relay, operator and executor entry points all call the store methods above. No other crate writes these tables directly. ## Tests The six PG tests are in `store::deletion::postgres_tests`. Each disables **only** its own trigger, then checks that the app path rejects the forbidden mutation and permits the allowed one: - `single_table_guard_channels_remain_tenant_bound_without_trigger` - `single_table_guard_community_lifecycle_rejects_deleted_row_without_trigger`: icon refused while quiescing; fence refused on a deleted row; then the full fence→tombstone sequence; abort after tombstone fails. - `single_table_guard_abort_invalidates_generation_without_trigger`: abort from quiescing and from fenced, for unarchived and pre-archived communities; asserts active state, community and request generation = previous + 1, restored `archived_at`, null `deleted_at`. - `single_table_guard_request_inventory_freeze_is_one_way_without_trigger`: re-freeze is refused on both the operator and owner-preparation paths. The owner path leaves no approval evidence behind. Owner request-ID retargeting is refused, and a frozen manifest with missing JSON can't be filled in. - `single_table_guard_approval_evidence_is_append_only_without_trigger`: asserts the exact error. - `single_table_guard_manifest_chunks_stop_at_freeze_without_trigger` The source policy lives in `crates/buzz-db/tests/observability_source.rs` (`every_production_single_table_guard_writer_preserves_its_invariants`). It scans every crate's `src` directory and reuses the file's existing cfg-test stripping, comment and literal masking, function slicing and SQL normalization. Each rule is checked per function. A minimum count of discovered writers per table makes the test fail if discovery stops matching, and exact sets of production functions hit by each rule (lifecycle exemption, stamp exemption, chunk-guard callers, active-community writers, request-freeze writers) make it fail if a parser stops matching. The parser handles `ON CONFLICT … DO UPDATE SET` (with or without a space before `(`), tuple `SET (a, b) =`, and rejects column-less community inserts. A guard counts only as a plain conjunct of the statement's own WHERE: it must follow the WHERE start or an `AND` (optionally table-qualified, never `NOT`), with no whole-word `OR` outside the frozen-or-equal groups and no subquery, and every `destructive_storage_*` assignment must preserve a frozen value with `COALESCE`. Negative and accept fixtures cover every rule. The shared source filter now also skips `test_support.rs`, which is compiled only under `cfg(test)`. Each check was confirmed to fail when its fix is removed. Seven mutants each failed on an assertion: the `inventory_frozen_at` predicate removed from each of the two freeze paths, and each of the five policy rules disabled. Review rework also falsified the injected `SET icon = NULL` writer, an unguarded inventory/destructive-storage writer, abort keeping the old generation, and the stamp without `deleted_at IS NULL`; every new fixture test fails against the previous policy. Round 1 also falsified the lifecycle `deleted_at` check, the manifest append guard, the icon predicate and the destructive-manifest predicate. ## What got simpler The four lifecycle UPDATE statements, each with its own generation arithmetic and its own GUC setup, are now one transition function with one SQL writer. Both manifest removal modes share one admission check. For inventory freeze, the check lives in the existing atomic UPDATE, with no new helper or transaction. Channel immutability and approval append-only behavior stay construction rules, not duplicated runtime checks. The source-policy scans now share one Rust crate walker, which this PR extracted into `collect_production_rs_files`. **Known policy limits:** the policy is a textual check of Rust source, not a SQL parser or a control-flow analysis. None of these gaps hides an unsafe writer today, but phase-2 reviewers should not read the policy as more than that: - Only `INSERT`, `UPDATE` and `DELETE` statements are recognized, including CTE and `ON CONFLICT` forms. `MERGE` and `TRUNCATE` are not. `UPDATE ONLY <table>` and `DELETE FROM ONLY <table>` are not recognized either, because the table name must follow the verb directly. - A guard negated *after* itself (`deletion_state = 'active' IS FALSE`, `… = false`) is not caught. - A SQL comment inside the literal (`-- AND deletion_state = 'active'`) can supply the guard text. - The frozen-or-equal `OR` text is removed before the `OR` check without checking how it is grouped. - `guard_manifest_chunk_write(` is checked for presence in the writing function only. The policy does not show the result is awaited and propagated, or that the guard runs in the same transaction as the write. With the trigger disabled, `single_table_guard_manifest_chunks_stop_at_freeze_without_trigger` shows append and pre-freeze clear refusing after freeze; verified cleanup has no trigger-disabled test. - Function discovery uses a fixed list of signature prefixes, and dynamic SQL is recognized only in known shapes such as `set_parts.push`. - The shared source filter skips files named `test_support.rs` by name. Both such files are compiled only under `cfg(test)` today. **Phase 2 (not here):** a forward migration plus a desired-state change will drop only these five triggers and functions and update `validate_serving_catalog_on` and the schema assertions. It ships after every serving and executor pod runs these writers. **Identified debt (pre-existing, outside this diff):** purge can take the request-row FK lock (checkpoint insert) before the community lock, while abort locks community then request (`deletion.rs` purge vs abort). PostgreSQL detects that as a deadlock and cancels one side, which fails closed; the order is unchanged from the base. `runtime::postgres_tests::writer_pool_rejects_non_read_committed_database_default` hangs until its 120 s bound on clean `177551dda` as well. Some test-only fallbacks still hardcode `localhost:5432`, and one relay test helper hardcodes Redis 6379. ## Verification (Blox, byte-identical tree to this commit) | Gate | Result | |---|---| | `cargo fmt --all -- --check` | pass | | `cargo clippy --workspace --all-targets -- -D warnings` | pass | | `cargo nextest run -p buzz-db --lib` | 166/166 | | `cargo nextest run -p buzz-db --test observability_source` | 30/30 | | `scripts/test-postgres-test-discovery.sh` | pass | | `scripts/postgres-test-run.sh -p` buzz-admin / audit / deletion / push-gateway / relay / search / workflow | all rc 0 (4, 7, 11, 11, 402, 20, 2) | | `scripts/postgres-test-run.sh -p buzz-db` | 515 pass, 1 fail: the pre-existing hang above | The new PG tests are selected by the `postgres-ci` filter `(test(/postgres_tests::/) or binary(/^postgres_/)) and not test(/(^|::)external_infra[^:]*::/)`. The policy tests run in `just test-unit` (`--test observability_source`). --------- Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Signed-off-by: Luke Tornquist <tornquist@squareup.com> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
3d97535120 | buzz-db: check workflow references in app code before FK retirement (#9399) |